Created
November 8, 2016 12:02
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I guess I'll use this until there is consistent browser support for the native closest() function cough IE, Edge