Skip to content

Instantly share code, notes, and snippets.

@PhilippeVay
Created November 28, 2017 11:32
Show Gist options
  • Save PhilippeVay/444dd4d8e5ace1abd6d63086d9686012 to your computer and use it in GitHub Desktop.
Save PhilippeVay/444dd4d8e5ace1abd6d63086d9686012 to your computer and use it in GitHub Desktop.
Equivalent in JavaScript to .closest() from jQuery (MS and modern browsers)
// Source: https://stackoverflow.com/q/18663941/137626 (answers #1 Ales and #2 Joon)
function sgClosest(el, selector) {
var matchesFn;
// find vendor prefix (@NOTE-phv Limited to MS here, other prefixes are ditched)
['matches', 'msMatchesSelector'].some( function (fn) {
if (typeof document.body[fn] == 'function') {
matchesFn = fn;
return true;
}
return false;
});
var parent;
// traverse parents
while (el) {
parent = el.parentElement;
if (parent && parent[matchesFn](selector)) {
return parent;
}
el = parent;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment