Last active
December 9, 2018 02:16
-
-
Save paulirish/5537058 to your computer and use it in GitHub Desktop.
jQuery.fn.closest equivalent in DOM js
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
// starting with current element, look up the DOM ancestor tree to see if anything matches the given selector | |
// returns element if found | |
// returns false if not found | |
function closest(elem, selector) { | |
var matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector; | |
while (elem) { | |
if (matchesSelector.bind(elem)(selector)) { | |
return elem; | |
} else { | |
elem = elem.parentNode; | |
} | |
} | |
return false; | |
} |
:( This got solved?
matchesSelector.call(elem, selector)
(at least works in Chrome)
Nice snippet but use elem.parentElement not paretNode and you will get rid of the illegal invocation error.
Is it planned somewhere to add this as an Element method by some spec?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Illegal invocation, come onnnnnnnnnn