Element. closest()
Returns the nearest ancestor (or the element itself) matching a CSS selector, or null.
- Returns
- The nearest matching element (which can be the element itself), or
null.
Example
#const icon = document.querySelector('.icon')
console.log(icon.closest('button'))
console.log(icon.closest('.card').dataset.id)
console.log(icon.closest('.sidebar'))
console.log(icon.closest('span') === icon)Definition and usage
#The closest() method walks up the DOM tree starting from the element: it checks the element itself first, then its parent, grandparent, and so on. It returns the first element matching the selector, or null if it reaches the top of the document without finding anything.
This is a core tool for event delegation. When a user clicks an icon inside a button, and the button sits inside a product card, event.target.closest(".card") finds the card right away, regardless of which part of it was clicked.
Keep in mind that closest() includes the element it starts from. It works in the opposite direction from querySelector(), which searches downward, among descendants.
Syntax
#element.closest(selectors)Parameters
#selectors
string
A CSS selector, e.g.".card","li", or"[data-id]".
More examples
#const catalog = document.querySelector('#catalog')
catalog.addEventListener('click', (event) => {
const button = event.target.closest('.buy')
if (!button) return
const card = button.closest('.card')
console.log(`Added to cart: ${card.dataset.course}`)
})
catalog.querySelector('b').click()const menu = document.querySelector('#menu')
document.addEventListener('click', (event) => {
if (!event.target.closest('#menu')) {
menu.classList.remove('open')
}
console.log('Menu open:', menu.classList.contains('open'))
})
document.querySelector('#menu button').click()
document.querySelector('#content').click()Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- With event delegation, always check whether
closest()found something (if (!button) return), since the click might have landed elsewhere. - Remember that
closest()also checks the element itself:button.closest("button")returns that same button. querySelector()is for searching downward, among descendants.
Related entries
#- Event.targetThe element on which an event actually occurred, for example the clicked button inside a list.
- document.querySelector()Returns the first element that matches a CSS selector, or null when nothing matches.
- EventTarget.addEventListener()Registers a function that’s called every time a given event occurs on an element, for example a click.
- HTMLElement.datasetAn object with an element’s data-* attribute values, for reading and storing your own data.
Spotted a mistake or missing an example? Write to us.