nearest ancestor node in jQuery

后端 未结 4 1723
情歌与酒
情歌与酒 2021-01-07 23:53

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(

相关标签:
4条回答
  • 2021-01-08 00:36

    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.

    0 讨论(0)
  • 2021-01-08 00:36

    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()

    0 讨论(0)
  • 2021-01-08 00:43

    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.

    0 讨论(0)
  • 2021-01-08 00:47

    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).

    0 讨论(0)
提交回复
热议问题