Parent selector

Parent selector

I am trying to figure out if it is possible to select elements on a page where the element itself OR a parent element (at any level) has a certain class. 

Explained in more detail:

Base function:
  1. $(SELECTOR).each(function() {
  2. Do something;
  3. });

Example html:

  1. <ul>
  2.       <li>A</li>
  3.       <li class="y">B
  4.         <ul id="1">
  5.           <li id="2">1</li>
  6.           <li id="3">2</li>
  7.           <li id="4">3</li>
  8.         </ul>
  9.       </li>
  10.       <li id="5" class="y">C</li>
  11. </ul>
The selector would search for elements with either itself having class y or a parent element at any level with the class y. So from the code above the elements with id 1,2,3,4 and 5 would be selected.

Any help appreciated.