jQuery 如何使用jquery查找元素的第n个父元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8180320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find nth parent of an element using jquery
提问by Rakhitha Nimesh
I want to find the nth parent element of an given element and access the attributes of parent.
我想找到给定元素的第 n 个父元素并访问父元素的属性。
<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 的第三个父元素而不使用
$('#element1').parent().parent().parent()
Any help would be appreciated
任何帮助,将不胜感激
回答by Richard Dalton
You can use .parents()
and .eq()
:
您可以使用.parents()
和.eq()
:
$('#element1').parents().eq(2);
回答by DidThis
回答by 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);
回答by Alex
use:
用:
$('#element1').closest('#parent1');