Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 。)   ask by rvighne translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
519 views
Welcome To Ask or Share your Answers For Others

1 Answer

Update: Now supported in most major browsers(更新:现在大多数主流浏览器都支持)

document.querySelector("p").closest(".near.ancestor") Note that this can match selectors, not just classes(请注意,这可以匹配选择器,而不仅仅是类) https://developer.mozilla.org/en-US/docs/Web/API/Element.closest(https://developer.mozilla.org/en-US/docs/Web/API/Element.closest) For legacy browsers that do not support closest() but have matches() one can build selector-matching similar to @rvighne's class matching:(对于不支持nearest closest()但有matches()旧版浏览器,可以构建类似于@ rvighne类匹配的选择器匹配:) function findAncestor (el, sel) { while ((el = el.parentElement) && !((el.matches || el.matchesSelector).call(el,sel))); return el; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...