Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

javascript - 找到具有特定类的最近的祖先元素(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 。)   ask by rvighne translate from so

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

1 Reply

0 votes
by (71.8m points)

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; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...