Domanda

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.

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:

<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'));

È stato utile?

Soluzione

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.

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

Altri suggerimenti

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.

$('.select').filter(function() {
    return $(this).closest('.forbidden').length == 0;
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top