如何获取所有可能具有祖先的元素,并且它们的所有祖先都没有指定的类

How to get all elements which possibly have ancestors and all their ancestors are without a specified class?

本文关键字:祖先 元素 获取 有可能 何获取      更新时间:2023-09-26

我的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>

我已经把上面的代码放在这个JSFiddle中。我已经使用没有 jQuery 的 document.querySelectorAll 函数测试了两个选择器,行为是相同的。

谢谢! :-)

:not(.a) .b:not(.a)

选择具有类 b 但没有类 a 的所有元素,这些元素具有任何没有类 a 的祖先,例如 <body> & <html>

:not(.a) > .b:not(.a)

选择具有类 b、不带类 a 且没有类 a直接父级的所有元素。

你的意思是选择.b元素

  • .a,并且
  • 没有任何祖先.a

那么这只能用jQuery来做(了解更多(:

$(".b:not(.a, .a *)")

如果需要在 CSS 中执行此操作,可以使用带有上述选择器的 jQuery 添加一个类,也可以使用覆盖:

.b {
  /* Style all .b elements */
}
.a .b, .a.b {
  /* Override the previous rule */
}