Vanilla JavaScript Closest

Today we are looking into the JavaScript closest() method, what it is, how it works, and a demo on using it.

What is the JavaScript closest method?

It's a method in JavaScript which finds the closest parent to a specific element. It accepts a selector, so the syntax looks like this:

var closestElement = myElement.closest(selectors);

In this syntax, the myElement is from where we will start searching. The method will look upwards until it finds the selector we specified.

The selector can be a DOMString, e.g.: a:hover, label + input

HTML Structure

To test we are going to make the following HTML structure:

<article>
  <div class="grand-parent">
    <div class="parent">
      <a href="#">
        <div id="myElement">This is me</div>
      </a>
    </div>
  </div>
</article>

Using the Closest Method

var myElement = document.getElementById('myElement');

var closest1 = myElement.closest('.parent');
console.log(closest1); // div class = parent

var closest2 = myElement.closest('div div');
console.log(closest2); // div id = myElement

var closest3 = myElement.closest('a');
console.log(closest3); // a href element

var closest4 = myElement.closest(':not(div)');
console.log(closest4); // a href element

var closest5 = myElement.closest('article');
console.log(closest5); // the Article

var closest6 = myElement.closest('article > div');
console.log(closest6); // Div with grand-parent class

As you can see it's a very versatile method which accept multiple ways of getting what we want.

See and try for yourself on Codepen.

View on Codepen.

Browser Support

The method is not supported in IE (Boooh!), but we can use a Polyfill for it!

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Tapas Adhikary's photo

Daily Dev Tips, Thanks for sharing, I was not much aware of Closest.

Just one point on formatting the article. You may have to format the view on codepen section.

Chris Bongers's photo

Thanks man, missed that one. Kinda silly the codepen doesn't render inside the article :(...

How did you get it to work in the comments?

Tapas Adhikary's photo

Daily Dev Tips ,

Welcome!

I did this,

%[https://codepen.io/rebelchris/pen/WNryVgp]

Bolaji Ayodeji's photo

Thanks for sharing :)

Chris Bongers's photo

Your welcome!