找到具有特定类的最接近的祖先元素 [英] Find the closest ancestor element that has a specific class
问题描述
如何在纯JavaScript 中找到最靠近树上的元素的祖先,具有特定的类?例如,在像这样的树中:
How can I find an element's ancestor that is closest up the tree that has a particular class, in pure JavaScript? For example, in a tree like so:
<div class="far ancestor">
<div class="near ancestor">
<p>Where am I?</p>
</div>
</div>
然后我想要 div.near.ancestor
如果我在 p
上尝试这个,并搜索 ancestor
。
Then I want div.near.ancestor
if I try this on the p
and search for ancestor
.
推荐答案
这样做的技巧:
function findAncestor (el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
while循环等待直到 el
具有所需的类,并且将 el
设置为 el
的父进程,所以最后,你有这个类的祖先,或者 null
。
The while loop waits until el
has the desired class, and it sets el
to el
's parent every iteration so in the end, you have the ancestor with that class or null
.
这是一个小提琴,如果有人想改进它。它不会在旧浏览器(即IE)上运行;请参阅 classList兼容性表。 parentElement
在这里使用,因为 parentNode
将涉及更多的工作,以确保节点是一个元素。
Here's a fiddle, if anyone wants to improve it. It won't work on old browsers (i.e. IE); see this compatibility table for classList. parentElement
is used here because parentNode
would involve more work to make sure that the node is an element.
这篇关于找到具有特定类的最接近的祖先元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!