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.
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