简体   繁体   English

选择所有其父级没有特定类的元素(使用'.not()')

[英]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;
});

I would not use :not . 我不会使用: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。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM