如何在jquery中找到第一个父元素 [英] How to find first parent element in jquery
问题描述
下面的html -
< div class =container1>
< div class =container2>
< div class =container3>
< div class =container4>
< div class =element>
...
< / div>
< / div>
< / div>
< / div>
如果我想获得< div class =element>
元素,我参考了 container1
。在jquery中,我做的是
$(。container1)。find(。element)
而不是 -
$(。container1)。children()。children()。children()。find(。element)
当我引用任何父元素时,这是查找任何子元素的过程。但是,当我引用一个子元素并想要获取父元素时,每次我必须去一级 -
$(。element)。parent()。parent()。parent()。parent()
我不能这样做 -
$(。element)。findParent()$ b $我没有碰到jquery中的findParent()方法。有没有我不知道的?或者是因为某些原因不存在?解决方案
$(。element 。父母();
将给所有的父母 .element
em>(包括 html
和 body
)
找到任何特定的父母,假设 container1
然后
$('。 ').parents('。container1')
jQuery .parents()
通常找到所有的父母,但如果你传递一个选择器,那么它将搜索。
Conside below 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,
$(".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?
解决方案 $(".element").parents();
will give all parents of .element
(including html
and body
)
To find any specific parent, suppose container1
then
$('.element').parents('.container1')
jQuery .parents()
generally find all parents, but if you passed a selector then it will search for that.
这篇关于如何在jquery中找到第一个父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!