选择父母没有某个类的所有元素(使用'.not()')

时间:2021-08-13 21:18:23

I am trying to select all elements with the class .select which are nested somewhere in the DOM-tree.
The only restriction is, they're not allowed to have any parents with the class .forbidden.

我试图用类.select选择所有元素,这些元素嵌套在DOM树中的某个地方。唯一的限制是,他们不允许任何父母上课.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? Something like this: $('.select').not($(this).parents().hasClass('.forbidden'));

如何使用.not()函数实现此选择?像这样:$('。select')。not($(this).parents()。hasClass('。forbidden'));

3 个解决方案

#1


6  

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. contains elements, there is an element somewhere up the DOM tree with that class.

您需要检查父元素,并使用该类找到的第一个元素处的nearest()停止,以及选择器是否具有长度,即。包含元素,在DOM树的某个地方有一个元素。

$('.select').filter(function(){
     return !$(this).closest('.forbidden').length;
});

#2


4  

I would not use :not.

我不会用:不。

But I would use filter :

但我会使用过滤器:

$('.select').filter(function(){return !$(this).parents().is('.forbidden')});

Note that is returns true if at least one element of the set (here the parents) matches the selector.

请注意,如果集合中的至少一个元素(此处为父元素)与选择器匹配,则返回true。

#3


3  

$('.select').filter(function() {
    return $(this).closest('.forbidden').length == 0;
});

#1


6  

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. contains elements, there is an element somewhere up the DOM tree with that class.

您需要检查父元素,并使用该类找到的第一个元素处的nearest()停止,以及选择器是否具有长度,即。包含元素,在DOM树的某个地方有一个元素。

$('.select').filter(function(){
     return !$(this).closest('.forbidden').length;
});

#2


4  

I would not use :not.

我不会用:不。

But I would use filter :

但我会使用过滤器:

$('.select').filter(function(){return !$(this).parents().is('.forbidden')});

Note that is returns true if at least one element of the set (here the parents) matches the selector.

请注意,如果集合中的至少一个元素(此处为父元素)与选择器匹配,则返回true。

#3


3  

$('.select').filter(function() {
    return $(this).closest('.forbidden').length == 0;
});