logo
post image

Writing jQuery closest() in Pure Javascript

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

The jQuery code to find the closest ancestor would be :

$("#outer-3").closest("#outer-1")

You can write the same code in Javascript as :

document.querySelector("#outer-3").closest("#outer-1")

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),
            i,
            el = this;
        do {
            i = matches.length;
            while (--i >= 0 && matches.item(i) !== el) {};
        } while ((i < 0) && (el = el.parentElement)); 
        return el;
    };
}