Skip to content Skip to sidebar Skip to footer

Nearest Ancestor Node In JQuery

In my javascript experience, I found that is a very common task 'searching the nearest ancestor of an element with some condition (tag name, class,...)'. Can the parents() method

Solution 1:

Edit: Since jQuery 1.3, this has been built in as the closest() function. eg: $('#foo').closest('.bar');


yep - parents() traverses up the tree.

<div id="a">
    <div id="b">
        <p id="c">
            <a id="d"></a>
        </p>
    </div>
</div>

$('#d').parents("div:first"); will select div b.


Solution 2:

Adding to @nickf's answer:

jQuery 1.3 simplifyed this task with closest.

Given a DOM:

<div id="a">
    <div id="b">
        <p id="c">
            <a id="d"></a>
        </p>
    </div>
</div>

You can do:

$('#d').closest("div"); // returns [ div#b ]

[Closest returns a] set of elements containing the closest parent element that matches the specified selector, the starting element included.


Solution 3:

You should use closest, because parents won't give you the result you expect if you're working with multiple elements. For instance, let's say you have this:

    <div id="0">
        <div id="1">test with <b>nested</b> divs.</div>
        <div id="2">another div.</div>
        <div id="3">yet <b>another</b> div.</div>
    </div>

and you want to add a class to the divs that have a <b> element as their immediate child (ie, 1 and 3). If you use $('b').parents('div'), you get divs 0, 1 and 3. If you use $('b').parents('div:first'), you only get div 1. To get 1 and 3, but not 0, you have to use $('b').closest(elem).


Solution 4:

closest() starts at current element, if the parent you are looking for has the same tag as current (eg. both are divs), use parent().closest()


Post a Comment for "Nearest Ancestor Node In JQuery"