Created
November 28, 2017 11:32
-
-
Save PhilippeVay/444dd4d8e5ace1abd6d63086d9686012 to your computer and use it in GitHub Desktop.
Equivalent in JavaScript to .closest() from jQuery (MS and modern browsers)
This file contains hidden or 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
// 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