Writing jQuery closest() in Pure Javascript

Published on April 16, 2017

Similar to $.closest() there exists a native Javascript function closest().

As an example see the below markup :

<div id="outer-1">
	<div id="outer-2">
		<div id="outer-3"><div>

The jQuery code to find the closest ancestor would be :


You can write the same code in Javascript as :


Browser Compatibility & Polyfill

closest function is fairly new. As of now all browsers, except IE have implemented it.

There is a polyfill available for older browsers. The below polyfill code is taken directly from Mozilla :

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