Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Element.closest — nearest matching ancestor

Element.closest(selectors) checks the element and then its ancestors. It returns the first element matching the CSS selector, or null.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

element.closest(selectors)

Element.closest(selectors) is a DOM method, not part of ECMAScript itself. It checks the calling element first, then its parent and successive ancestors. It returns the nearest matching Element, or null.

The selectors argument is a CSS selector string. Invalid syntax throws a DOMException named SyntaxError, rather than returning null. The method neither searches descendants nor crosses from a shadow tree to its host.

The example checks the nearest ancestor, a self-match, and no match. The tree need not be attached to the document.

Examples

const outer = document.createElement('section');
const inner = document.createElement('div');
const button = document.createElement('button');
outer.className = 'panel';
inner.className = 'panel';
outer.append(inner);
inner.append(button);

console.log(button.closest('.panel') === inner);
console.log(button.closest('button') === button);
console.log(button.closest('.missing'));

Result

true
true
null

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources