Element: closest() メソッド
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2017年4月.
closest()
は Element
インターフェイスのメソッドで、この要素とその親に(文書ルートに向かって)、指定された CSS セレクターに一致するノードが見つかるまで探索します。
構文
js
closest(selectors)
引数
返値
selectors
に一致する最も近い祖先の Element
または自分自身です。そのような要素がない場合は null
を返します。
例外
SyntaxError
DOMException
-
selectors
が有効なセレクターリストの文字列ではない場合に発生します。
例
>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");
// "div-02" の id を持つ直近の祖先
console.log(el.closest("#div-02")); // <div id="div-02">
// div の中にある div である直近の祖先
console.log(el.closest("div div")); // <div id="div-03">
// div であって親に article がある直近の祖先
console.log(el.closest("article > div")); // <div id="div-01">
// div ではない直近の祖先
console.log(el.closest(":not(div)")); // <article>
仕様書
Specification |
---|
DOM> # ref-for-dom-element-closest①> |
ブラウザーの互換性
Loading…
互換性のメモ
- Edge 15-18 では、要素が最初に(直接的または間接的に)コンテキストオブジェクト、例えば通常の DOM の場合は
Document
オブジェクトに接続されていない場合、document.createElement(tagName).closest(tagName)
がnull
を返します。
関連情報
- CSS セレクターモジュール
- セレクターを取る他の
Element
のメソッド:Element.querySelector()
,Element.querySelectorAll()
,Element.matches()