Question

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

Was it helpful?

Solution

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

OTHER TIPS

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;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top