Javascript 如何在jquery中找到第一个父元素

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

How to find first parent element in jquery

javascriptjqueryhtmldom

提问by Ashwin

Conside below html -

考虑下面的html -

<div class="container1">
   <div class="container2">
      <div class="container3">
         <div class="container4">
             <div class="element">
             ...
         </div>
      </div>
   </div>
</div>

if I want to get <div class="element">element and I have reference to the container1. In jquery what I do is,

如果我想获取<div class="element">元素并且我参考了container1. 在 jquery 中,我所做的是,

$(".container1").find(".element")

instead of -

代替 -

$(".container1").children().children().children().find(".element")

This is process to find any child element when I have reference to any of the parent element. But instead when I have reference to a child element and want to get parent element then every time I have to go one level up -

这是当我引用任何父元素时查找任何子元素的过程。但是,当我引用子元素并想要获取父元素时,每次我都必须上一级时 -

$(".element").parent().parent().parent().parent()

and I can't do like this -

我不能这样做 -

$(".element").findParent()

I have not come across any method like findParent() in jquery. Is there which I am not aware of? Or is it not there for some reason?

我还没有在 jquery 中遇到任何像 findParent() 这样的方法。有什么我不知道的吗?还是因为某种原因不存在?

回答by thecodeparadox

$(".element").parents();

will give all parents of .element(including htmland body)

将给所有父母.element(包括htmlbody

DEMO

演示

To find any specific parent, suppose container1then

要找到任何特定的父母,假设container1然后

$('.element').parents('.container1')

DEMO

演示

jQuery .parents()generally find all parents, but if you passed a selector then it will search for that.

jQuery.parents()通常会找到所有的父节点,但是如果你传递了一个选择器,它就会搜索它。

回答by Fabrizio Calderan

just use

只是使用

$(".element").closest('#container1');

if no ancestor with that idis found then

如果没有id找到祖先,那么

$(".element").closest('#container1').lengthwill be 0

$(".element").closest('#container1').length将会 0

回答by Paul Basenko

To get the first parent personally I use the following construction:

为了亲自获得第一个父母,我使用以下结构:

var count_parents = $(".element").parents().length;
$(".element").parents().eq(count_parents - 1);

Hope, it will be helpful for someone.

希望,这会对某人有所帮助。