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

一曲冷凌霜 提交于 2019-12-18 18:46:31

问题


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


回答1:


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




回答2:


Try li:not(.foo > ul > li); that selects all lis minus those with a parent .foo two levels up.




回答3:


You can do it using context along with selector as under,

$('li', $('div:not(.foo)'))

LIve Demo

$('li', $('div:not(.foo)')).each(function(){
    alert($(this).text());
});​



回答4:


How about this:

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

The comments in the docs are quite useful if this doesn't work:

http://api.jquery.com/not-selector/




回答5:


I think this solution looks a little nicer, but there's a bit of controversy on the API comments about speed differences.

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

fiddle



来源:https://stackoverflow.com/questions/13881198/select-element-unless-it-has-an-ancestor-of-a-given-class-using-just-a-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!