Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sounisi5011/f6f4b915fa8ab68ed3df to your computer and use it in GitHub Desktop.
Save sounisi5011/f6f4b915fa8ab68ed3df to your computer and use it in GitHub Desktop.
Element.matches & Element.closest Polyfill
/**
* @see https://dom.spec.whatwg.org/#interface-element
* @see https://developer.mozilla.org/docs/Web/API/Element/matches#Polyfill
* @see https://gist.github.com/jonathantneal/3062955
* @see https://github.com/jonathantneal/closest
*/
(function(global){
var Element;
var ElementPrototype;
var matches;
if (Element = global.Element) {
ElementPrototype = Element.prototype;
/**
* @see https://dom.spec.whatwg.org/#dom-element-matches
*/
if (!(matches = ElementPrototype.matches)) {
if ((
matches = ElementPrototype.matchesSelector ||
ElementPrototype.mozMatchesSelector ||
ElementPrototype.msMatchesSelector ||
ElementPrototype.oMatchesSelector ||
ElementPrototype.webkitMatchesSelector ||
(ElementPrototype.querySelectorAll && function matches(selectors) {
var element = this;
var nodeList = (element.parentNode || element.document || element.ownerDocument).querySelectorAll(selectors);
var index = nodeList.length;
while (--index >= 0 && nodeList.item(index) !== element) {}
return index > -1;
})
)) {
ElementPrototype.matches = matches;
}
}
/**
* @see https://dom.spec.whatwg.org/#dom-element-closest
*/
if (!ElementPrototype.closest && matches) {
ElementPrototype.closest = function closest(selectors) {
var element = this;
while (element) {
if (element.nodeType === 1 && element.matches(selectors)) {
return element;
}
element = element.parentNode;
}
return null;
};
}
}
}(Function('return this')()));
!function(a){var c;if(a=a.Element)a=a.prototype,!(c=a.matches)&&(c=a.matchesSelector||a.mozMatchesSelector||a.msMatchesSelector||a.oMatchesSelector||a.webkitMatchesSelector||a.querySelectorAll&&function matches(a){a=(this.parentNode||this.document||this.ownerDocument).querySelectorAll(a);for(var b=a.length;0<=--b&&a.item(b)!==this;);return-1<b})&&(a.matches=c),!a.closest&&c&&(a.closest=function closest(a){for(var b=this;b;){if(1===b.nodeType&&b.matches(a))return b;b=b.parentNode}return null})}(Function("return this")());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment