Skip to content

Instantly share code, notes, and snippets.

@andreasvirkus
Created September 16, 2016 14:09
Show Gist options
  • Save andreasvirkus/1b6ab7603ea5dfa434eabec1d11220ed to your computer and use it in GitHub Desktop.
Save andreasvirkus/1b6ab7603ea5dfa434eabec1d11220ed to your computer and use it in GitHub Desktop.
/**
* Vanilla JS implementation of $.closest()
*
* @param {Node|HTMLElement|*} el Starting point element
* @param {String} selector Selector to match parent element against
* @returns {*} Element node if found, otherwise null
*/
function closestEl(el, selector) {
var matchesSelector = el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector;
while (el) {
if (matchesSelector.call(el, selector)) {
return el;
} else {
el = el.parentNode;
}
}
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment