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>

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;
jQuery to Pure Javascript, Part 1 : Selectors
Writing jQuery find() in Pure Javascript