Table of contents
1.
Introduction
2.
What is JavaScript closest() Method?
2.1.
Key Features:
3.
Syntax of JavaScript closest() Method
3.1.
Syntax
4.
Parameters of JavaScript closest() Method
5.
Return Value of JavaScript closest() Method
6.
How Does It Work?  
7.
Exceptions of JavaScript closest() Method
7.1.
Example of SyntaxError:
8.
Example
9.
More Examples
9.1.
Example 1: Finding the closest form element
9.2.
Example 2: When no matching element is found
10.
Supported Browsers
11.
Frequently Asked Questions
11.1.
What is the difference between closest() and querySelector()?
11.2.
What happens if closest() does not find a matching element?
11.3.
Can closest() be used on dynamically created elements?
12.
Conclusion
Last Updated: Feb 12, 2025
Medium

JavaScript closest() Method

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The JavaScript closest() method is used to find the nearest ancestor of an element that matches a specified selector. This method helps developers easily navigate the DOM tree to locate parent elements, which is particularly useful for event delegation and DOM manipulation. If no matching ancestor is found, it returns null

JavaScript closest() Method

In this article, we will learn about the JavaScript closest() method, how it finds the nearest ancestor element that matches a specified selector.

What is JavaScript closest() Method?

The closest() method is a built-in JavaScript function that allows you to traverse the DOM upwards and find the nearest ancestor that matches a specified CSS selector. It is commonly used in event delegation and dynamic content manipulation.

Key Features:

  • Returns the element itself if it matches the selector.
     
  • Traverses up the DOM tree to find a match.
     
  • Returns null if no match is found.
     
  • Works efficiently for dynamic elements.

Syntax of JavaScript closest() Method

The closest() method is applied on a DOM element and searches for the nearest ancestor, including itself, that matches the specified CSS selector.

Syntax

let closestElement = element.closest(selector);

 

Explanation:

  • element: The starting point of the search.
     
  • selector: A valid CSS selector used to find the closest ancestor.
     
  • closestElement: The nearest ancestor matching the selector or null if no match is found.

Parameters of JavaScript closest() Method

The closest() method takes a single parameter:

ParameterDescription
selectorA string representing a CSS selector to match against ancestor elements.

Return Value of JavaScript closest() Method

The closest() method returns:

  • The nearest ancestor element (including the element itself) that matches the selector.
     
  • null if no matching ancestor is found.

How Does It Work?  

The `closest()` method takes one argument: a CSS selector string. It checks if the current element matches the selector. If it doesn’t, the method moves up to the parent element and repeats the process until it either finds a match or reaches the top of the DOM tree.  

For example: 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Closest Method Example</title>
  <style>
    .card {
      border: 2px solid black;
      padding: 10px;
      margin: 10px;
    }
  </style>
</head>
<body>
  <div class="card">
    <h2>Card Title</h2>
    <p>This is some text inside the card.</p>
    <button id="myButton">Click Me</button>
  </div>

  <script>
    // Select the button element
    const button = document.getElementById('myButton');

    // Add a click event listener to the button
    button.addEventListener('click', function() {
      // Use closest() to find the nearest ancestor with the class 'card'
      const card = button.closest('.card');

      // Check if a matching element was found
      if (card) {
        console.log('Found the card element:', card);
      } else {
        console.log('No matching ancestor found.');
      }
    });
  </script>
</body>
</html>


In this code:  

1. HTML Structure: We have a `div` with the class `card`. Inside it, there’s a heading, a paragraph, and a button.  
 

2. JavaScript Logic:  

  • First, we select the button using `document.getElementById('myButton')`.  
     
  • Then, we attach a `click` event listener to the button.  
     
  • Inside the event listener, we use the `closest()` method to find the nearest ancestor with the class `card`. 
     
  • If a match is found, it logs the element to the console. Otherwise, it logs a message saying no match was found.  

Exceptions of JavaScript closest() Method

The closest() method does not throw exceptions under normal circumstances. However, if an invalid CSS selector is passed, it may throw a SyntaxError.

Example of SyntaxError:

try {
    let element = document.querySelector("#myElement");
    let closestDiv = element.closest("123invalidSelector");
} catch (error) {
    console.error("Invalid selector:", error.message);
}

 

Output:

Invalid selector: Failed to execute 'closest' on 'Element': '123invalidSelector' is not a valid selector.

Example

Let's see a basic example of using closest().

<!DOCTYPE html>
<html lang="en">
<head>
    <title>JavaScript closest() Example</title>
</head>
<body>
    <div id="parent">
        <div class="child">
            <p id="para">Click me!</p>
        </div>
    </div>

    <script>
        let para = document.getElementById("para");
        let closestDiv = para.closest("div");
        console.log(closestDiv.id); // Output: "parent"
    </script>
</body>
</html>

 

Explanation:

  • The closest("div") method starts from <p> and checks its ancestors.
     
  • It finds the first <div> (id="parent") and returns it.

More Examples

Example 1: Finding the closest form element

<form id="myForm">
    <div>
        <button id="submitBtn">Submit</button>
    </div>
</form>
<script>
    let button = document.getElementById("submitBtn");
    let closestForm = button.closest("form");
    console.log(closestForm.id); // Output: "myForm"
</script>

Example 2: When no matching element is found

<div>
    <p id="text">Hello!</p>
</div>
<script>
    let text = document.getElementById("text");
    let closestSpan = text.closest("span");
    console.log(closestSpan); // Output: null
</script>

Supported Browsers

The closest() method is widely supported in modern browsers:

BrowserSupport
ChromeYes
FirefoxYes
SafariYes
EdgeYes
OperaYes
Internet ExplorerNo


If you need support for Internet Explorer, you can use a polyfill:

if (!Element.prototype.closest) {
    Element.prototype.closest = function(selector) {
        let element = this;
        do {
            if (element.matches(selector)) return element;
            element = element.parentElement;
        } while (element !== null);
        return null;
    };
}

Frequently Asked Questions

What is the difference between closest() and querySelector()?

  • closest() searches up the DOM tree to find the nearest ancestor that matches the selector.
     
  • querySelector() searches down the DOM tree from the given element.

What happens if closest() does not find a matching element?

It returns null, meaning no ancestor matched the given selector.

Can closest() be used on dynamically created elements?

Yes, closest() works efficiently with dynamically created elements, making it useful in event delegation.

Conclusion

In this article, we learned about the JavaScript closest() method, which helps find the nearest parent element that matches a specific selector. We discussed how it works by moving up the DOM tree to locate the matching element. Understanding the closest() method is important for handling DOM events and interacting with HTML elements more efficiently in JavaScript.

Live masterclass