Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery closest exclude self

Tags:

jquery

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'));
    });
});
like image 254
Joe.wang Avatar asked Mar 26 '13 03:03

Joe.wang


3 Answers

You can traverse a level up before trying to find the .closest() ancestor:

$(this).parent().closest('.container');
like image 160
Fabrício Matté Avatar answered Sep 26 '22 23:09

Fabrício Matté


Vanilla js:

el.parentElement.closest('.container')

Jquery:

el.parent().closest('.container');
like image 31
yaya Avatar answered Sep 23 '22 23:09

yaya


The right answer is .parents('.container:first'); thanks

like image 45
Joe.wang Avatar answered Sep 22 '22 23:09

Joe.wang