找到最近的具有特定类的祖先元素 - 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章