# 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

`element.closest('selector');`

## Example

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

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

The code execution result:

`'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:

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

The code execution result:

`'child'`

## See also

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

← →
↑
en ru