語法
js
closest(selectors)
引數
返回值
最近的祖先 Element 或自身,它匹配 selectors。如果沒有找到這樣的元素,則返回 null。
異常
SyntaxErrorDOMException-
如果
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()。