Cover Image for JavaScript closest()
151 views

JavaScript closest()

The closest() method in JavaScript is used to find the closest ancestor element that matches a specific selector. It starts with the current element and traverses up the DOM tree until it finds a matching element or reaches the root element.

The closest() method accepts a selector as an argument and returns the closest ancestor element that matches the selector. If no matching element is found, it returns null.

Here’s an example usage of the closest() method:

HTML<span role="button" tabindex="0" data-code="<div> <h2>Hello</h2> <ul> <li>Item 1</li> <li class="highlight">Item 2</li> <li>Item 3</li> </ul>
<div>
  <h2>Hello</h2>
  <ul>
    <li>Item 1</li>
    <li class="highlight">Item 2</li>
    <li>Item 3</li>
  </ul>
</div>
JavaScript<span role="button" tabindex="0" data-code="const listItem = document.querySelector('.highlight'); const closestDiv = listItem.closest('div'); console.log(closestDiv); // Output: <div>…
const listItem = document.querySelector('.highlight');
const closestDiv = listItem.closest('div');

console.log(closestDiv); // Output: <div>...</div>

In this example, we have an unordered list (ul) with list items (li). The second list item has a class of “highlight”. We use the querySelector() method to select the list item with the class “highlight”. Then, we use the closest() method with the selector “div” to find the closest ancestor div element. The result is assigned to the closestDiv variable. Finally, we log the closestDiv to the console.

The closest() method is particularly useful when you want to find a specific ancestor element based on a given selector, such as finding a parent container or a specific element within the DOM tree.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS