我一直在浏览有关 JavaScript 的 MDN 文档,并发现了 Element.closest
属性。这仍然只是一个实验属性,但了解如何使用它很重要。
这是规范的内容
The Element.closest() method returns the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter. If there isn't such an ancestor, it returns null.
https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
var par = document.getElementById('my-id');
par.closest("h2").style.background = "yellow";
<div id="first">
<h2>Heading</h2>
<div id="second">
<div id="third">
<p id="my-id">This is a paragraph</p>
</div>
</div>
</div>
我使用最新版本的 Google Chrome。根据兼容性图表,这应该适用于 Google Chrome 41+
我找不到任何不起作用的原因。
有什么理论吗?
最佳答案
正如您所说,此方法返回最近的祖先
,具体取决于您输入的选择器
。在您的情况下,h2
不是#my-id
的祖先,并且它也无法返回自身,因为它们不是同一类型,因此结果为 null。如果将 p#my-id
更改为 h2#my-id
它将起作用:
它在这个例子中工作:
var par = document.getElementById('my-id');
par.closest("h2").style.background = "yellow"; //returns itself
par.closest("#first").style.color = "red"; // change color of an ancestor
<div id="first">
<h2>Heading</h2>
<div id="second">
<div id="third">
<h2 id="my-id">This is a paragraph</h2>
</div>
</div>
</div>
关于JavaScript - Element.closest 未设置样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35785684/