Skip to content

Instantly share code, notes, and snippets.

@electerious
Last active November 6, 2015 22:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save electerious/b045e45572c463756b2c to your computer and use it in GitHub Desktop.
Save electerious/b045e45572c463756b2c to your computer and use it in GitHub Desktop.
Select the closest matching parent of an element
const closest = (elem, className) => {
if (elem==null || elem.classList==null) return null
return (elem.classList.contains(className) ? elem : closest(elem.parentNode, className))
}
@electerious
Copy link
Author

Example:

closest(document.querySelector('.inner'), 'outer')

Alternatives:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment