問題:
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