Skip to content

Instantly share code, notes, and snippets.

@oelna
Created November 8, 2016 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oelna/fc3983d640c39d88551cc05b63504a5b to your computer and use it in GitHub Desktop.
Save oelna/fc3983d640c39d88551cc05b63504a5b to your computer and use it in GitHub Desktop.
A vanilla javascript method that returns the closest DOM ancestor that matches a selector, or null.
var closest = function(selector, ele) {
if(!selector || !ele) return null;
//polyfill .matches()
if(Element && !Element.prototype.matches) {
Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector;
}
if(ele.matches(selector)) return ele; //return self if it matches
var parent = ele.parentNode;
var i = 0;
while(!parent.matches(selector)) {
parent = parent.parentNode;
if(parent.tagName == undefined) return null; //reached the end of the DOM tree
if(i >= 100) return null; //emergency break
i += 1;
}
return parent;
}
@oelna
Copy link
Author

oelna commented Nov 8, 2016

I guess I'll use this until there is consistent browser support for the native closest() function cough IE, Edge

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment