Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get only top level elements

Tags:

jquery

nested

I need to get only the first matched elements from my tree (if element was found no need to go deeper). The problem is that this element can be wrapped into nested divs, so I can't use > selector.
My code is like this:

<div id="root">
    <div class="sub">I need this element</div>
    <div>
        <div class="sub">I need this element</div>
    </div>
    <div class="sub">
        <div class="sub">I don't need this element</div>
    </div>
</div>

Can't find solution :(

like image 389
Lebovski Avatar asked Jan 28 '26 07:01

Lebovski


1 Answers

If you can't use the child selector, try

$('.sub:not(.sub .sub)')

This selects only those .sub elements which are not descendants of other .sub elements.

Alternatively:

$('#root .sub').filter(function() {
    return $(this).parentsUntil('#root', '.sub').length === 0;
});

which also works if #root is inside a .sub.

Edit: Or see @RightSaidFred's comment for this case.

like image 136
Felix Kling Avatar answered Jan 30 '26 20:01

Felix Kling