Skip to content

Instantly share code, notes, and snippets.

@paulirish
Last active December 9, 2018 02:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save paulirish/5537058 to your computer and use it in GitHub Desktop.
Save paulirish/5537058 to your computer and use it in GitHub Desktop.
jQuery.fn.closest equivalent in DOM js
// 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;
}
@rasmusx
Copy link

rasmusx commented Mar 17, 2014

Nice snippet but use elem.parentElement not paretNode and you will get rid of the illegal invocation error.

@kof
Copy link

kof commented Jun 28, 2014

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