语法
js
closest(selectors)
参数
返回值
最近的祖先 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
。
另见
- CSS 选择器模块
- 其他接受选择器的
Element
方法包括:Element.querySelector()
、Element.querySelectorAll()
和Element.matches()
。