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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:10:55  来源:igfitidea点击:

How to find nth parent of an element using jquery

jquerydomnavigationparent

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

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

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

回答by DidThis

parents()returns a list, so this works:

parent()返回一个列表,所以这有效:

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

回答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');