How to find nth parent of an element using jquery

拥有回忆 提交于 2019-11-28 20:50:46

问题


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

<div id='parent1'><br/>
  <div id='parent2'><br/>
       <span><p id='element1'>Test</p></span><br/>
  </div><br/>
  <div id='parent3'><br/>
       <span><p id='element2'>Test</p></span><br/>
  </div><br/>
</div>

I want to access the 3rd parent element of element1 without using

$('#element1').parent().parent().parent()

Any help would be appreciated


回答1:


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

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

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




回答2:


parents() returns a list, so this works:

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



回答3:


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



回答4:


use:

$('#element1').closest('#parent1');


来源:https://stackoverflow.com/questions/8180320/how-to-find-nth-parent-of-an-element-using-jquery

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