Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. Element
  4. closest()

Element: closest() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017.

Theclosest() method of theElement interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specifiedCSS selector.

Syntax

js
closest(selectors)

Parameters

selectors

A string of validCSS selectors to match theElement and its ancestors against.

Return value

The closest ancestorElement or itself, which matches theselectors. If there are no such element,null.

Exceptions

SyntaxErrorDOMException

Thrown if theselectors is not a valid CSS selector.

Examples

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");// the closest ancestor with the id of "div-02"console.log(el.closest("#div-02")); // <div>// the closest ancestor which is a div in a divconsole.log(el.closest("div div")); // <div>// the closest ancestor which is a div and has a parent articleconsole.log(el.closest("article > div")); // <div>// the closest ancestor which is not a divconsole.log(el.closest(":not(div)")); // <article>

Specifications

Specification
DOM
# ref-for-dom-element-closest①

Browser compatibility

Compatibility notes

  • In Edge 15-18document.createElement(tagName).closest(tagName) willreturnnull if the element is not first connected (directly orindirectly) to the context object, for example theDocument object inthe case of the normal DOM.

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp