このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。
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 セレクターに一致するノードが見つかるまで探索します。
In this article
構文
js
closest(selectors)引数
返値
selectors に一致する最も近い祖先のElement または自分自身です。そのような要素がない場合はnull を返します。
例外
SyntaxErrorDOMExceptionselectorsが有効なセレクターリストの文字列ではない場合に発生します。
例
>HTML
html
<article> <div> Here is div-01 <div> Here is div-02 <div>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>// div の中にある div である直近の祖先console.log(el.closest("div div")); // <div>// div であって親に article がある直近の祖先console.log(el.closest("article > div")); // <div>// div ではない直近の祖先console.log(el.closest(":not(div)")); // <article>仕様書
| Specification |
|---|
| 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()