JavaScript polyfills for matches,closest, and forEach.
// https://github.com/jonathantneal/closest/blob/master/src/index.js | |
var ElementPrototype = window.Element.prototype; | |
if (typeof ElementPrototype.matches !== 'function') { | |
ElementPrototype.matches = ElementPrototype.msMatchesSelector || ElementPrototype.mozMatchesSelector || ElementPrototype.webkitMatchesSelector || function matches(selector) { | |
var element = this; | |
var elements = (element.document || element.ownerDocument).querySelectorAll(selector); | |
var index = 0; | |
while (elements[index] && elements[index] !== element) { | |
++index; | |
} | |
return Boolean(elements[index]); | |
}; | |
} | |
if (typeof ElementPrototype.closest !== 'function') { | |
ElementPrototype.closest = function closest(selector) { | |
var element = this; | |
while (element && element.nodeType === 1) { | |
if (element.matches(selector)) { | |
return element; | |
} | |
element = element.parentNode; | |
} | |
return null; | |
}; | |
} | |
// https://gist.github.com/hufyhang/c303ce1b80c7b6f8a73e | |
if (!Array.prototype.forEach) { | |
Array.prototype.forEach = function forEach (callback, thisArg) { | |
if (typeof callback !== 'function') { | |
throw new TypeError(callback + ' is not a function'); | |
} | |
var array = this; | |
thisArg = thisArg || this; | |
for (var i = 0, l = array.length; i !== l; ++i) { | |
callback.call(thisArg, array[i], i, array); | |
} | |
}; | |
} | |
// https://vanillajstoolkit.com/polyfills/nodelistforeach/ | |
if (window.NodeList && !NodeList.prototype.forEach) { | |
NodeList.prototype.forEach = function (callback, thisArg) { | |
thisArg = thisArg || window; | |
for (var i = 0; i < this.length; i++) { | |
callback.call(thisArg, this[i], i, this); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment