closest()
will get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. But I want to know if there is any way to get the result excluding itself (I mean just get the parents of it).
Let me take a example. Please review it.
<div id='div1' class="container">
<div id="div2" class="container">
<!--many nested div.container as it directly or indirectly children -->
</div>
<div id="div3" class="container">
<!--many nested div.container as it directly or indirectly children -->
</div>
</div>
$(function() {
$('div.container').on('mouseover', function(e){
//I only want to select the first parent with the class container.
//closest include the this element.
console.log($(this).closest('.container').attr('id'));
});
});
You can traverse a level up before trying to find the .closest()
ancestor:
$(this).parent().closest('.container');
Vanilla js:
el.parentElement.closest('.container')
Jquery:
el.parent().closest('.container');
The right answer is .parents('.container:first');
thanks
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