Element:closest() 方法

Baseline 已广泛支持

该特性已非常成熟,可在多种设备和浏览器版本上使用。自 2017 年 4 月以来,它已在各大浏览器上可用。

closest() 方法属于 Element 接口,它会遍历当前元素及其父元素(朝向文档根方向),直到找到一个匹配指定 CSS 选择器的节点。

语法

js
closest(selectors)

参数

选择器 (selectors)

一个有效的 CSS 选择器字符串,用于匹配 Element 及其祖先节点。

返回值

最近的祖先 Element 或自身,它匹配 selectors。如果没有找到这样的元素,则返回 null

异常

SyntaxError DOMException

如果 selectors 不是有效的 CSS 选择器,则会抛出异常。

示例

HTML

html
<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>

JavaScript

js
const el = document.getElementById("div-03");

// the closest ancestor with the id of "div-02"
console.log(el.closest("#div-02")); // <div id="div-02">

// the closest ancestor which is a div in a div
console.log(el.closest("div div")); // <div id="div-03">

// the closest ancestor which is a div and has a parent article
console.log(el.closest("article > div")); // <div id="div-01">

// the closest ancestor which is not a div
console.log(el.closest(":not(div)")); // <article>

规范

规范
DOM
# ref-for-dom-element-closest①

浏览器兼容性

兼容性说明

  • 在 Edge 15-18 中,如果元素未首先(直接或间接)连接到上下文对象(例如,正常 DOM 的情况下的 Document 对象),则 document.createElement(tagName).closest(tagName) 会返回 null

另见