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 :(
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With