Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select element unless it has an ancestor of a given class using just a selector

Tags:

Suppose I have the following HTML:

<div class="foo">   <ul>     <li>One</li>     <li>Two</li>   </ul> </div> <!-- not originally here --> <div class="bar">   <ul>     <li>Three</li>     <li>Four</li>   </ul> </div> 

I want to select all li elements that are not descendants of an element with class foo. I know I can do it with a fancy filter function, but I'm wondering whether I can do it with just a selector. First I tried:

$(":not(.foo) li") 

Unfortunately this doesn't work since the li has other ancestors without the style (the ul in this case). The following seems to work;

$(":not(.foo) :not(.foo) li") 

In other words, select all li elements that have no ancestor that either has class foo or has an ancestor of its own with class foo. Perhaps this is the best/only way to do it with a selector, but I'm not thrilled about the repetition of the :not selector. Any better ideas out there?

fiddle

like image 806
Matthew Gertner Avatar asked Dec 14 '12 15:12

Matthew Gertner


1 Answers

You can do it like this

$("li").not('.foo li') 

http://jsfiddle.net/y7s54/

or

$("li:not(.foo li)") 

http://jsfiddle.net/QpCYY/

Select all li's that don't have an ancestor with class foo

like image 89
wirey00 Avatar answered Oct 15 '22 03:10

wirey00