JavaScript - Element.closest 未设置样式

标签 javascript html dom

我一直在浏览有关 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/

相关文章:

javascript - 将 image.src 设置为自身会导致 onLoad 触发吗?

javascript - Angular JS 在 ng-repeat 中设置点击对象的值

javascript - 如何在 node.js 和 SQLite3 中使用 document.querySelector 和 require

javascript - 如何在多个元素上但不同时使用 toggleClass

javascript - 随机报价脚本

android - 我如何使用 Jquery Mobile 实现 MVC 架构

javascript - 谷歌地图标记的动态图标变化

jquery - 如何使用CSS翻转div?

javascript - 如何将现有的 D3 SVG 图表添加回 DOM?

javascript - 为什么 Javascript 事件处理程序会更改我的 PHP 变量?