问题:
How can I find an element's ancestor that is closest up the tree that has a particular class, in pure JavaScript ?如何在纯 JavaScript 中找到最靠近具有特定类的树的元素的祖先? For example, in a tree like so:例如,在这样的树中:
<div class="far ancestor">
<div class="near ancestor">
<p>Where am I?</p>
</div>
</div>
Then I want div.near.ancestor
if I try this on the p
and search for ancestor
.然后我想要div.near.ancestor
如果我在p
上尝试这个并搜索ancestor
。
解决方案:
参考一: https://stackoom.com/question/1UoKv参考二: Find the closest ancestor element that has a specific class