Skip to content

Instantly share code, notes, and snippets.

@adactio
Created November 9, 2020 17:19
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adactio/e2bcd49379d4385e577924ec3339aeb1 to your computer and use it in GitHub Desktop.
Save adactio/e2bcd49379d4385e577924ec3339aeb1 to your computer and use it in GitHub Desktop.
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