选择元素,除非它具有仅使用选择器的给定类的祖先 [英] Select element unless it has an ancestor of a given class using just a selector
问题描述
假设我具有以下HTML:
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>
我想选择所有不是类foo
的元素的不是后代的li
元素.我知道我可以使用精美的过滤器来完成此操作功能,但我想知道是否可以仅使用选择器就能做到这一点.首先,我尝试过:
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")
不幸的是,这不起作用,因为li
有 other 个祖先,但没有样式(在本例中为ul
).以下似乎有效;
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")
换句话说,选择所有不具有祖先的所有li
元素,这些祖先要么具有类foo
,要么具有其自身的祖先,而其祖先具有类foo
.也许这是使用选择器的最佳/唯一方法,但是对于:not
选择器的重复,我并不感到兴奋.还有更好的主意吗?
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?
推荐答案
您可以这样做
$("li").not('.foo li')
或
$("li:not(.foo li)")
选择所有不具有foo类祖先的li'
Select all li's that don't have an ancestor with class foo
这篇关于选择元素,除非它具有仅使用选择器的给定类的祖先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!