Search code examples
javascriptjqueryhtmldomdom-traversal

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


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