Skip to content

Instantly share code, notes, and snippets.

@farinspace
Created November 15, 2019 17:31
Show Gist options
  • Save farinspace/c183ac09435885d527e8ed0a6564aac5 to your computer and use it in GitHub Desktop.
Save farinspace/c183ac09435885d527e8ed0a6564aac5 to your computer and use it in GitHub Desktop.
Element.closest(selector) polyfill
/**
* Element.closest(selector) polyfill
*
* https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
*/
(function(){
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
}
if (!Element.prototype.closest) {
Element.prototype.closest = function(s) {
var el = this;
do {
if (el.matches(s)) return el;
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
};
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment