Movatterモバイル変換


[0]ホーム

URL:


  1. 開発者向けのウェブ技術
  2. Web API
  3. Element
  4. closest()

このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。

View in EnglishAlways switch to English

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

有効なCSS セレクターを表す文字列です。これをこの要素 (Element) およびその祖先に向けて照合します。

返値

selectors に一致する最も近い祖先のElement または自分自身です。そのような要素がない場合はnull を返します。

例外

SyntaxErrorDOMException

selectors が有効なセレクターリストの文字列ではない場合に発生します。

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 を返します。

関連情報

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp