问题描述
更新:现在大多数主流浏览器都支持
document.querySelector("p").closest(".near.ancestor")
请注意,这可以匹配选择器,而不仅仅是类
https://developer.mozilla.org/en- US/docs/Web/API/Element.closest
对于不支持closest()
但有matches()
一个的旧版浏览器可以构建类似于@rvighne 的类匹配的选择器匹配:
function findAncestor (el, sel) {
while ((el = el.parentElement) && !((el.matches || el.matchesSelector).call(el,sel)));
return el;
}
解决方法
如何 在纯 JavaScript 中 找到最靠近具有特定类的树的元素的祖先?例如,在这样的树中:
<div class="far ancestor">
<div class="near ancestor">
<p>Where am I?</p>
</div>
</div>
然后我想div.near.ancestor
如果我尝试这个p
并搜索ancestor
.