找到具有特定类的最近的祖先元素

我如何才能找到一个元素的祖先是最接近的树,有一个特定的类,纯JavaScript?例如,在这样的树中:

<div class="far ancestor">
<div class="near ancestor">
<p>Where am I?</p>
</div>
</div>

然后我想要div.near.ancestor,如果我在p上尝试这个并搜索ancestor

326487 次浏览

这招很管用:

function findAncestor (el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}

while循环一直等待到el拥有所需的类,并在每次迭代时将el设置为el的父类,因此最后,您拥有该类或null的祖先。

这是小提琴,如果有人想改善它。它不能在旧的浏览器(即IE)上工作;请看这个classList的兼容性表。这里使用parentElement,因为parentNode将涉及更多的工作,以确保节点是一个元素。

更新:现在支持在大多数主流浏览器中

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

下面是基于the8472回答https://developer.mozilla.org/en-US/docs/Web/API/Element/matches的跨平台2017解决方案:

if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function(s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length;
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1;
};
}


function findAncestor(el, sel) {
if (typeof el.closest === 'function') {
return el.closest(sel) || null;
}
while (el) {
if (el.matches(sel)) {
return el;
}
el = el.parentElement;
}
return null;
}

@rvighne解决方案工作得很好,但正如评论中所指出的,ParentElementClassList都有兼容性问题。为了使它更加兼容,我使用了:

function findAncestor (el, cls) {
while ((el = el.parentNode) && el.className.indexOf(cls) < 0);
return el;
}
  • parentNode属性而不是parentElement属性
  • className属性上使用indexOf方法而不是classList属性上的contains方法。

当然,indexOf只是查找该字符串是否存在,它并不关心它是否是整个字符串。因此,如果您有另一个具有'祖宗类型'类的元素,它仍然会返回为已找到'祖宗',如果这对您来说是一个问题,也许您可以使用regexp来找到精确匹配。

使用< em > element.closest () < / em >

https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

请看这个例子DOM:

<article>
<div id="div-01">Here is div-01
<div id="div-02">Here is div-02
<div id="div-03">Here is div-03</div>
</div>
</div>
</article>

下面是使用element. nearest的方法:

var el = document.getElementById('div-03');


var r1 = el.closest("#div-02");
// returns the element with the id=div-02


var r2 = el.closest("div div");
// returns the closest ancestor which is a div in div, here is div-03 itself


var r3 = el.closest("article > div");
// returns the closest ancestor which is a div and has a parent article, here is div-01


var r4 = el.closest(":not(div)");
// returns the closest ancestor which is not a div, here is the outmost article

此解决方案应该适用于IE9及以上版本。

它就像jQuery的parents()方法,当你需要获得一个父容器时,它可能比给定的元素高几层,比如找到一个被单击的<button>的包含<form>。遍历父类,直到找到匹配的选择器,或者直到它到达<body>。返回匹配的元素或<body>

function parents(el, selector){
var parent_container = el;
do {
parent_container = parent_container.parentNode;
}
while( !parent_container.matches(selector) && parent_container !== document.body );


return parent_container;
}