HTML | DOM closest() Method

The closest() method of the element interface is used to traverse the element and its parents in the HTML Document Tree until it finds the first node that matches the selector string that is provided.


targetElement.closest( selectors )

Parameters: This method accepts a single parameter as mentioned above and described below:

  • selectors: It is a string that specifies the HTML selectors that will be used to find the node.

Return Value: This method returns the closest element if the matching ancestor is found, otherwise it returns null if no such element is found.

Example: The following example shows the usage of closest() method by searching the given elements in HTML DOM structure.






<!DOCTYPE html>
            Hello! it is a span
            <p id="p">It is paragraph</p>
        // Get the paragraph element
        var element = document.getElementById('p');
        // Return the closest paragraph element
        // which is the element itself
        var close1 = element.closest("p");
        // Return the closest span element 
        var close2 = element.closest("span");
        // Return the closest div element
        var close3 = element.closest("div");



The element which is the closest to the selector is returned.


Supported Browsers: The browsers supported by DOM closest() method are listed below:

  • Google Chrome
  • Edge
  • Firefox
  • Apple Safari
  • Opera


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.