Skip to content

Instantly share code, notes, and snippets.

@paulirish
Last active January 4, 2025 15:01
Show Gist options
  • Select an option

  • Save paulirish/5537058 to your computer and use it in GitHub Desktop.

Select an option

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;
}
@kof
Copy link
Copy Markdown

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