Element

Element.prototype.closest

Traverses the element and its parents toward the document root until it finds an element that matches the specified CSS selector

Syntax

JavaScript
element.closest(selectors)

Parameters

ParameterTypeDescription
selectorsstringA string containing CSS selectors to match

Return Value

The closest ancestor Element matching the selector, or null

Examples

Basic Usage
const button = document.querySelector('button')!
const form = button.closest('form')
console.log(form?.id)
Practical Example
document.addEventListener('click', (e) => {
  const row = (e.target as HTMLElement).closest('tr')
  if (row) console.log('Clicked row:', row.rowIndex)
})
Advanced Usage
function getSection(el: HTMLElement): HTMLElement | null {
  return el.closest('section, article, main')
}

Understanding Element.prototype.closest

The Element.prototype.closest method in JavaScript traverses the element and its parents toward the document root until it finds an element that matches the specified CSS selector. It belongs to the Element object and is one of the most widely used methods for working with element values in modern JavaScript and TypeScript applications.

The method signature is element.closest(selectors). It accepts 1 parameter: selectors. When called, it returns the closest ancestor element matching the selector, or null. Understanding when and how to use closest() helps you write more expressive, readable code.

Common use cases for Element.prototype.closest include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-matches, dom-queryselector, dom-parentelement, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for Element.prototype.closest is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More Element Methods

Other methods in the Element object

Related Tools

More Element Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.