How to find nth parent of an element using jquery

前端 未结 4 1910
忘掉有多难
忘掉有多难 2020-12-24 10:43

I want to find the nth parent element of an given element and access the attributes of parent.


相关标签:
4条回答
  • 2020-12-24 11:16

    You can use .parents() and .eq():

    $('#element1').parents().eq(2);
    

    http://jsfiddle.net/infernalbadger/4YmYt/

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

    use:

    $('#element1').closest('#parent1');
    
    0 讨论(0)
  • 2020-12-24 11:25

    parents() returns a list, so this works:

    $('#element1').parents()[2];
    
    0 讨论(0)
  • 2020-12-24 11:26

    You could make a little plugin to take care of that:

    $.fn.nthParent = function(n){
        var p = this;
        for(var i=0;i<n;i++)
            p = p.parent();
        return p;
    }
    

    and then use it as:

    $('#element1').nthParent(3);
    
    0 讨论(0)
提交回复
热议问题