[英]Selecting all elements whose parents don't have a certain class (using '.not()')
I am trying to select all elements with the class .select
which are nested somewhere in the DOM-tree. 我试图选择所有嵌套在DOM树中某个位置的类
.select
元素。
The only restriction is, they're not allowed to have any parents with the class .forbidden
. 唯一的限制是,他们不允许任何父母参加
.forbidden
。
So it would not find any elements in following tree part: 因此,它将在以下树部分中找不到任何元素:
<div>
<div class="forbidden">
<div>
<div>
<div class="select">Some Content</div>
</div>
</div>
</div>
</div>
But would find 1 element in here: 但是会在这里找到1个元素:
<div>
<div>
<div>
<div>
<div>
<div class="select">Some Content</div>
</div>
</div>
</div>
</div>
</div>
How can I achieve this selection by using the .not()
function? 如何使用
.not()
函数来实现此选择? Something like this: $('.select').not($(this).parents().hasClass('.forbidden'));
像这样的东西:
$('.select').not($(this).parents().hasClass('.forbidden'));
You'll need to check for parent elements, and closest()
stops at the first element found with that class, and if the selector has length, ie. 您需要检查父元素,并且
closest()
停在该类找到的第一个元素上,并且选择器是否具有长度,即。 contains elements, there is an element somewhere up the DOM tree with that class. 包含元素,则该类在DOM树上的某个位置有一个元素。
$('.select').filter(function(){
return !$(this).closest('.forbidden').length;
});
$('.select').filter(function() {
return $(this).closest('.forbidden').length == 0;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.