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
element.closest(selectors)Parameters
| Parameter | Type | Description |
|---|---|---|
| selectors | string | A string containing CSS selectors to match |
Return Value
The closest ancestor Element matching the selector, or null
Examples
const button = document.querySelector('button')!
const form = button.closest('form')
console.log(form?.id)document.addEventListener('click', (e) => {
const row = (e.target as HTMLElement).closest('tr')
if (row) console.log('Clicked row:', row.rowIndex)
})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
Element.prototype.matchesTests whether the element would be selected by the specified CSS selector string
document.querySelectorReturns the first Element within the document that matches the specified CSS selector, or null if no matches are found
Element.prototype.parentElementReturns the parent Element of the specified element, or null if the element has no parent or the parent is not an Element
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.