X



Home>Tutorial>

What is JavaScript closest() and Examples

Nuelson Penuel Monday, July 31, 2023 Javascript

Table Of Contents

Meaning of JavaScript closest()

JavaScript closest() Syntax

JavaScript closest() Method Example

Conclusion

</div>

Meaning of JavaScript closest()

The `closest()` method in JavaScript is a function that allows you to find the closest ancestor element that matches a specific CSS selector or condition. It is a part of the Element Traversal API and is available on DOM elements.

JavaScript closest() Syntax

Here's the syntax for using `closest()`:
element.closest(selector);
The `element` is the DOM element on which you want to perform the search, and `selector` is the CSS selector or condition that you want to match against the ancestors. The `closest()` method starts from the current element and searches upward through its ancestors in the DOM tree until it finds an element that matches the given selector. If a match is found, that element is returned. If no match is found, the method returns `null`.

JavaScript closest() Method Example

Here's an example to illustrate the `closest()` method: Html
<div>
  <ul>
    <li>
      <a href="#" class="link">Click me!</a>
    </li>
  </ul>
</div>
JavaScript
var linkElement = document.querySelector('.link');
var listItemElement = linkElement.closest('li');
console.log(listItemElement); // Output: <li>...</li>
In the above example, the `closest()` method is used to find the nearest ancestor `
  • ` element of the `` element with the class "link". It searches upward through the ancestor elements until it finds a match and returns the `
  • ` element. If there is no matching ancestor element, the `closest()` method returns `null`. For instance:
    var divElement = linkElement.closest('div');
    console.log(divElement); // Output: &lt;div&gt;...&lt;/div&gt;
    
    In this case, there is a matching `<div>` element as an ancestor, so it is returned. But if you use a selector that doesn't match any ancestor element, it will return `null`:
    var spanElement = linkElement.closest('span');
    console.log(spanElement); // Output: null
    

    Conclusion

    The `closest()` method is useful when you want to target specific ancestor elements in the DOM tree based on a certain condition or selector. It allows you to efficiently traverse the DOM hierarchy and find the element you need without manually iterating through multiple layers of ancestors.

  • | | Views(106)

    See Demo | Download File


    Add your comment. Indicate code using code tag


    Words: 0 | Chars: 0 | Reading Duration: 0



    Images Attachment




    Emmason Integratded Services(2017-2024)
    All Rights Reserved
    Designed and Maintained By Emmason Integrated Services