【发布时间】:2016-02-25 10:05:22
【问题描述】:
我的 HTML 的一部分与下面的相似,我必须只选择没有任何祖先的元素具有指定的类。我从事的项目非常大,我认为我不应该在这里发布所有代码,我认为这超出了 StackOverflow 的目的。
我想要的是按所有祖先过滤元素,而不仅仅是他们的父母。我试过这个:
// This colors two of the <span> elements instead of one. It colors the ".a > .b" <span> and this behavior seems wrong to me.
$(":not(.a) .b:not(.a)").css("color", "red");
// This call only colors the border of the ".b" <span> which, I think, is the correct behavior and should be the behavior of the call above.
$(":not(.a) > .b:not(.a)").css("border-color", "blue");
span {
border: 0.1rem solid gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
<span class="b">.a > .b</span> <!-- Why does this <span> element become red? -->
<span class="a b">.a > .a.b</span>
</div>
<div>
<span class="b">.b</span>
<span class="a b">.a.b</span>
</div>
我已将上面的代码放在this JSFiddle 中。我已经使用没有 jQuery 的 document.querySelectorAll 函数测试了这两个选择器,并且行为是相同的。
非常感谢! :-)
【问题讨论】:
-
如果你定义了你想要做什么,而不是解释这个 XY 问题,你的问题会更好。
-
@RoryMcCrossan,我已经更新了这个问题。我希望现在更好。
标签: javascript jquery html jquery-selectors css-selectors