How do I get the n-th level parent of an element in jQuery?

后端 未结 13 1937
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 10:24

When I want to get, for example, the 3rd level parent of the element I must write $(\'#element\').parent().parent().parent() Is there a more optimal method for

相关标签:
13条回答
  • 2020-12-12 10:59

    you can also use :

    $(this).ancestors().eq(n) 
    

    ex: $(this).ancestors().eq(2) -> the parent of the parent of this.

    0 讨论(0)
  • 2020-12-12 11:03

    You could give the target parent an id or class (e.g. myParent) and reference is with $('#element').parents(".myParent")

    0 讨论(0)
  • 2020-12-12 11:10

    Depends on your needs, if you know what parent your looking for you can use the .parents() selector.

    E.G: http://jsfiddle.net/HenryGarle/Kyp5g/2/

    <div id="One">
        <div id="Two">
            <div id="Three">
                <div id="Four">
    
                </div>
            </div>
        </div>
    </div>
    
    
    var top = $("#Four").parents("#One");
    
    alert($(top).html());
    

    Example using index:

    //First parent - 2 levels up from #Four
    // I.e Selects div#One
    var topTwo = $("#Four").parents().eq(2);
    
    alert($(topTwo ).html());
    
    0 讨论(0)
  • 2020-12-12 11:14

    using eq appears to grab the dynamic DOM whereas using .parent().parent() appears to grab the DOM that was initially loaded (if that is even possible).

    I use them both on an element that has classes applied it to on onmouseover. eq shows the classes while .parent().parent() doesnt.

    0 讨论(0)
  • 2020-12-12 11:16

    You could use something like this:

    (function($) {
        $.fn.parentNth = function(n) {
            var el = $(this);
            for(var i = 0; i < n; i++)
                el = el.parent();
    
            return el;
        };
    })(jQuery);
    
    alert($("#foo").parentNth(2).attr("id"));
    

    http://jsfiddle.net/Xeon06/AsNUu/

    0 讨论(0)
  • 2020-12-12 11:19

    It's simple. Just use

    $(selector).parents().eq(0); 
    

    where 0 is the parent level (0 is parent, 1 is parent's parent etc)

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