Subscribe

Vanilla JavaScript Closest

โœ๏ธ

What is the JavaScript closest method?

13 Jul, 2020 ยท 2 min read

Today we will learn about the Vanilla JavaScript closest method. We will find out what it is, how it works, and build a demo code to use it.

What is the JavaScript closest method?

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

const 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 and returns the matching ancestor element.

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

HTML Structure

To test the closest method, 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>

Example of using the Closest Method in Vanilla JavaScript

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

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

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

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

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

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

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

As you can see, it's a very versatile JavaScript method. It accepts multiple ways of getting the parent elements we want.

Try Vanilla JS closest() in this Codepen

Closest Vanilla JavaScript method code example WNryVgp by Chris Bongers (@rebelchris) on CodePen.

Browser Support for closest()

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

Element.closest support

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API

Join 1828 devs and subscribe to my newsletter