How to find nth parent of an element using jquery

﹥>﹥吖頭↗ 提交于 2019-11-30 03:07:16

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

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

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

gion_13

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

parents() returns a list, so this works:

$('#element1').parents()[2];

use:

$('#element1').closest('#parent1');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!