SoFunction
Updated on 2025-04-08

Detailed explanation of closest method example in JavaScript

Preface

In JavaScript,closest()is a very practical DOM method that helps us find the most recent ancestral element that meets the criteria from a certain DOM element. This method is ideal for use in event delegates and element lookup, especially when dealing with dynamic content or events.

What is the closest method?

closest()Method returns the current element (element) and its ancestor elements are the first to match the element that specifies the selector. If no elements match,closest()Will returnnull

grammar

(selector);
  • selector: A string that specifies the CSS selector to match ancestor elements. If specifiedselectorMatch the current element itself and it will also be returned.
  • Return value: Returns a DOM element object representing the closest ancestor element to match the current element. If there is no matching element, returnnull

How to use the closest method?

closest()The working principle of the method is: start with the current element, look up until you find the first ancestral element that meets the criteria (including yourself). If no element matching the criteria is found, it will returnnull

Example 1: Basic use

<div class="parent">
  <div class="child">
    <button >Click Me</button>
  </div>
</div>

<script>
  const btn = ('btn');
  
  // Find the nearest parent element (match class="child")  const closestDiv = ('.child');
  
  (closestDiv);  // Print .child element (<div class="child">...</div>)&lt;/script&gt;

In this example, the button element (#btn) passclosest('.child')Find and return its closest parent element (.child)。

Example 2: Find the current element itself

&lt;div class="parent"&gt;
  &lt;div class="child" &gt;Hello World&lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
  const myElement = ('myElement');
  
  // Find your own element (the element itself matches the selector)  const closestSelf = ('.child');
  
  (closestSelf);  // Print #myElement (<div class="child" >Hello World</div>)</script>

In this example,('.child')returnmyElementself, because it conforms to.childSelector.

Example 3: No matching elements

&lt;div class="parent"&gt;
  &lt;div class="child"&gt;
    &lt;button &gt;Click Me&lt;/button&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
  const btn = ('btn');
  
  // Find the nearest ancestor element (match .noneexistent)  const closestNonexistent = ('.nonexistent');
  
  (closestNonexistent);  // Output null&lt;/script&gt;

In this example, the button element (#btn) No on.nonexistentClass, soclosest()returnnull

Application scenarios of closest() method

  • Event delegation
    Event delegates are a common technique for attaching event listeners to parent elements instead of directly attaching them to each child element. This reduces memory usage and improves performance. When we process events, we often need to know the ancestor elements of the event target.closest()It's very useful.

    For example, suppose you have multiple in a listliElements, you want to click on a certainliTo perform certain operations, you can useclosest()Come find the nearest oneliElements.

    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>
    
    <script>
      ('ul').addEventListener('click', function(event) {
        const listItem = ('li');
        if (listItem) {
          ('You clicked on: ' + );
        }
      });
    </script>
    

    In this example, click anyliElements will be found in the nearestliElement and print out its text content. Even if you clickulNested elements (such as pictures or text),closest()The corresponding one can still be foundliElements.

  • Dynamic content
    Traditional event binding may fail when you have dynamically generated content because newly added elements do not have event bound. passclosest(), you can ensure that the event is properly bound to the parent element, thus avoiding this problem.

    For example, suppose you dynamically add a button, and when you click the button, we want to find its parent container:

    &lt;div class="container"&gt;
      &lt;div class="content"&gt;
        &lt;button class="action"&gt;Click Me&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    
    &lt;script&gt;
      const container = ('.container');
    
      // Dynamically add content  const newButton = ('button');
      ('action');
       = 'Click Me';
    
      ('.content').appendChild(newButton);
    
      // Event delegation  ('click', function(event) {
        const btn = ('.action');
        if (btn) {
          ('Button clicked:', );
        }
      });
    &lt;/script&gt;
    

    In this example,closest()Allows us to handle new dynamically generated buttons, because the event is in the parent element.containerBinded on.

Things to note

  • Closest() is looking for the nearest ancestor element
    It will look up from the current element starting with the current element until it finds a matching ancestor element. If the current element itself satisfies the selector condition, it will also be returned.

  • closest() will only look for the element's ancestor chain
    It does not look for child elements downwards. If you need to look up child elements down, you can usequerySelector()etc.

  • Processing when returning null
    When no matching ancestor element is found,closest()Will returnnull. Therefore, when using it, it is recommended to check the return value in case of errors.

    const result = ('.target');
    if (result !== null) {
      // Perform some operations} else {
      ('No matching ancestor element was found');
    }
    

Summarize

closest()is a very powerful DOM method that makes it more efficient when looking for ancestor elements. Not only does it work with event delegates, it also helps you easily find the ancestors of elements when dealing with complex DOM structures. In dynamic content and complex DOM interactions,closest()It is also a very convenient tool.

By masteringclosest()Methods, developers can operate DOM elements more flexibly and improve the maintainability and performance of their code.

This is the article about the detailed explanation of the closest method in JavaScript. For more related contents of the closest method in JS, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!