Javascript 如何在 jQuery 中获取元素的第 n 级父级?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7093659/
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-24 00:49:55  来源:igfitidea点击:

How do I get the n-th level parent of an element in jQuery?

javascriptjqueryparent

提问by Artur Keyan

When I want to get, for example, the 3rd level parent of the element I must write $('#element').parent().parent().parent()Is there a more optimal method for this?

例如,当我想获得必须编写的元素的第 3 级父级时,$('#element').parent().parent().parent()是否有更优化的方法?

回答by Frédéric Hamidi

Since parents()returns the ancestor elements ordered from the closest to the outer ones, you can chain it into eq():

由于parent()返回从最近到外部排序的祖先元素,您可以将其链接到eq()

$('#element').parents().eq(0);  // "Father".
$('#element').parents().eq(2);  // "Great-grandfather".

回答by Henry

Depends on your needs, if you know what parent your looking for you can use the .parents() selector.

取决于你的需要,如果你知道你在寻找什么父母,你可以使用 .parents() 选择器。

E.G: http://jsfiddle.net/HenryGarle/Kyp5g/2/

EG:http: //jsfiddle.net/HenryGarle/Kyp5g/2/

<div id="One">
    <div id="Two">
        <div id="Three">
            <div id="Four">

            </div>
        </div>
    </div>
</div>


var top = $("#Four").parents("#One");

alert($(top).html());

Example using index:

使用索引的示例:

//First parent - 2 levels up from #Four
// I.e Selects div#One
var topTwo = $("#Four").parents().eq(2);

alert($(topTwo ).html());

回答by Joseph Marikle

You could give the target parent an id or class (e.g. myParent) and reference is with $('#element').parents(".myParent")

你可以给目标父级一个 id 或类(例如 myParent),并且引用是 $('#element').parents(".myParent")

回答by a'r

A faster way is to use javascript directly, eg.

一种更快的方法是直接使用 javascript,例如。

var parent = $(innerdiv.get(0).parentNode.parentNode.parentNode);

This runs significantly faster on my browser than chaining jQuery .parent()calls.

这在我的浏览器上运行速度比链接 jQuery.parent()调用快得多。

See: http://jsperf.com/jquery-get-3rd-level-parent

请参阅:http: //jsperf.com/jquery-get-3rd-level-parent

回答by Dane

Didn't find any answer using closest()and I think it's the most simple answer when you don't know how many levels up the required element is, so posting an answer:
You can use the closest()function combined with selectors to get the first element that matches when traversing upwards from the element:

使用没有找到任何答案closest(),我认为这是最简单的答案,当您不知道所需元素的级别有多少时,因此发布答案:
您可以使用该closest()函数与选择器相结合来获取匹配的第一个元素当从元素向上遍历时:

('#element').closest('div')    // returns the innermost 'div' in its parents
('#element').closest('.container')    // returns innermost element with 'container' class among parents
('#element').closest('#foo')    // returns the closest parent with id 'foo'

回答by zatatatata

It's simple. Just use

这很简单。只需使用

$(selector).parents().eq(0); 

where 0 is the parent level (0 is parent, 1 is parent's parent etc)

其中 0 是父级(0 是父级,1 是父级的父级等)

回答by ashishyadaveee11

If you have a common parent div you can use parentsUntil() link

如果你有一个共同的父 div 你可以使用 parentsUntil()链接

eg: $('#element').parentsUntil('.commonClass')

例如: $('#element').parentsUntil('.commonClass')

Advantage is that you need not to remember how many generation are there between this element and the common parent(defined by commonclass).

优点是你不需要记住这个元素和公共父元素(由 commonclass 定义)之间有多少代。

回答by MBO

Just add :eq()selector like this:

只需:eq()像这样添加选择器:

$("#element").parents(":eq(2)")

You just specify index which parent: 0 for immediate parent, 1 for grand-parent, ...

您只需指定索引哪个父级:0 表示直接父级,1 表示祖父级,...

回答by zzzzBov

If you plan on reusing this functionality, the optimal solution is to make a jQuery plugin:

如果您打算重用此功能,最佳解决方案是制作一个 jQuery 插件:

(function($){
$.fn.nthParent = function(n){
  var $p = $(this);
  while ( n-- >= 0 )
  {
    $p = $p.parent();
  }
  return $p;
};
}(jQuery));

Of course, you may want to extend it to allow for an optional selector and other such things.

当然,您可能希望扩展它以允许可选的选择器和其他类似的东西。

One note: this uses a 0based index for parents, so nthParent(0)is the same as calling parent(). If you'd rather have 1based indexing, use n-- > 0

一个注意事项:这0对父项使用基于索引,因此nthParent(0)与调用parent(). 如果您更喜欢1基于索引,请使用n-- > 0

回答by Mouna Cheikhna

you can also use :

您还可以使用:

$(this).ancestors().eq(n) 

ex: $(this).ancestors().eq(2)-> the parent of the parent of this.

例如:$(this).ancestors().eq(2)-> 的父级的父级this