Skip to main content Accessibility Feedback

A native vanilla JavaScript way to get the closest matching parent element

Back in June, I showed you how to create a helper method, getClosest(), to find the closest parent element with a certain selector.

One of my readers told me about .closest(), a native element property that does the same thing.

var elem = document.querySelector('#some-element');
var closestParent = elem.closest('.pick-me');

The catch? It’s poorly supported by browsers.

But… there’s a polyfill you can use, and it’s less code than my helper function.

if (window.Element && !Element.prototype.closest) {
    Element.prototype.closest = 
    function(s) {
        var matches = (this.document || this.ownerDocument).querySelectorAll(s),
            i,
            el = this;
        do {
            i = matches.length;
            while (--i >= 0 && matches.item(i) !== el) {};
        } while ((i < 0) && (el = el.parentElement)); 
        return el;
    };
}

I’ll be using this instead of getClosest() on all future projects.


🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips