Vanilla JavaScript Closest

β€” 4 minute read

permalink

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? permalink

It's a method in JavaScript which finds the closest parent element to a specific HTML element. It accepts a CSS selector, so the JavaScript 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 and will then return the matching ancestor element.

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

HTML Structure permalink

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 permalink

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 JavaScript method. It accepts multiple ways of getting the parent elements we want.

Try Vanilla JS closest() in this Codepen permalink

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

Browser Support for closest() permalink

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! permalink

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