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

另見