JavaScriptDOM and events

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.
On this page

Example

#
JavaScript
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)
Console
<button class="buy">
7
null
true

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

#
Syntax
element.closest(selectors)

Parameters

#
  • selectors

    string

    A CSS selector, e.g. ".card", "li", or "[data-id]".

More examples

#
Event delegation
JavaScript
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()
Console
Added to cart: CSS
Closing a menu on an outside click
JavaScript
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()
Console
Menu open: true
Menu open: false

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

#

Spotted a mistake or missing an example? Write to us.