[英]How to get all elements which possibly have ancestors and all their ancestors are without a specified class?
I have a part of my HTML that is similar to the one below, and I must select only the elements that do not have any ancestors with a specified class. 我的HTML的一部分与下面的相似,并且我必须仅选择不具有指定类祖先的元素。 The project I work on is pretty big and I think I should not post here all the code, I think that would be beyond the purpose of StackOverflow.
我从事的项目很大,我认为我不应该在这里发布所有代码,我认为这超出了StackOverflow的目的。
What I want is filtering the elements by all their ancestors, not only by their parents. 我要的是过滤所有祖先的元素,而不仅仅是他们的父母。 I have tried this:
我已经试过了:
// 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="ab">.a > .ab</span> </div> <div> <span class="b">.b</span> <span class="ab">.ab</span> </div>
I have put the code above in this JSFiddle . 我已将代码放在此JSFiddle中 。 I have tested the two selectors using the
document.querySelectorAll
function without jQuery and the behavior is the same. 我已经在没有jQuery的情况下使用
document.querySelectorAll
函数测试了两个选择器,其行为是相同的。
Thank you very much! 非常感谢你!
:-)
:not(.a) .b:not(.a)
Selects all elements with class b , but without class a , that has any ancestor without class a , for example, <body>
& <html>
. 选择所有具有b类但不具有a类的元素,这些元素具有任何不具有a类的 祖先 ,例如
<body>
& <html>
。
:not(.a) > .b:not(.a)
Selects all elements with class b , without class a , that hasn't a direct parent with class a . 选择B级的所有元素,没有一流的 ,具有不与类 的直接父 。
Do you mean to select .b
elements that 您是要选择
.b
元素
.a
, and .a
和 .a
? .a
祖先 ? Then this is only doable with jQuery ( learn more ): 然后,这仅适用于jQuery( 了解更多信息 ):
$(".b:not(.a, .a *)")
If you need to do this in CSS, you can either add a class using jQuery with the above selector, or use an override: 如果您需要在CSS中执行此操作,则可以使用带有上述选择器的jQuery添加类,或使用重写:
.b {
/* Style all .b elements */
}
.a .b, .a.b {
/* Override the previous rule */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.