JavaScript closest()

The closest() method in JavaScript is used to retrieve the closest ancestor, or parent of the element matches the selectors. If there is no ancestor found, the method returns null.

This method traverses the element and its parents in the document tree, and the traversing continues until the first node is found that matches the provided selector string.

Syntax

In the above syntax, selectors is a string containing a selector (like p:hover, etc.) used to find a node.

Let's understand this method by using some illustrations.

Example1

In this example, there are three div elements and a heading on which we are applying the closest() method. Here, the selectors that we are using are the id selector, descendant selector, child selector, and :not selector.

Test it Now

Output

After the execution of the above code, the output will be -

JavaScript closest()

Example2

This is another example of using JavaScript's closest() method.

Test it Now

Output

After the execution of the above code, the output will be -

JavaScript closest()