closest method

The closest method searches for the closest parent element that matches the specified CSS selector, while the element itself is also included in the search.

Syntax

javascriptelement.closest('selector');

Example

Let's find among the parents of an element the element with the class www:

html<div class="www" id="parent2">
  <div class="ggg" id="parent1">
    <p class="zzz" id="child"></p>
  </div>
</div>
javascriptlet elem = document.querySelector('#child');
let parent = elem.closest('.www');

console.log(parent.id);

The code execution result:

javascript'parent2'

Example

Let's find among the parents of an element the element with the class www. As a result, we will get a reference to the element itself, since it has this class itself:

html<div class="www" id="parent2">
  <div class="www" id="parent1">
    <p class="www" id="child"></p>
  </div>
</div>
javascriptlet elem = document.querySelector('#child');
let parent = elem.closest('.www');
console.log(parent.id);

The code execution result:

javascript'child'

See also

  • the matches method
    that checks an element by a selector
  • the contains method
    that checks a child by a selector