Open In App

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.

Syntax:



targetElement.closest( selectors )

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

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 the closest() method by searching the given elements in the HTML DOM structure.




<!DOCTYPE html>
<html>
 
<head>
    <title>GeeksforGeeks</title>
</head>
 
<body>
    <div>
        <span>
            Hello! it is a span
            <p id="p">
                It is paragraph
            </p>
        </span>
    </div>
 
    <script>
        // Get the paragraph element
        let element = document.getElementById('p');
 
        // Return the closest paragraph element
        // which is the element itself
        let close1 = element.closest("p");
        console.log(close1)
 
        // Return the closest span element
        let close2 = element.closest("span");
        console.log(close2)
 
        // Return the closest div element
        let close3 = element.closest("div");
        console.log(close3)
    </script>
</body>
 
</html>

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

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


Article Tags :