找到最近的具有特定類的祖先元素 - Find the closest ancestor element that has a specific class

問題:

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章