Skip to content

Instantly share code, notes, and snippets.

@jimthoburn
Created September 8, 2016 01:24
Show Gist options
  • Save jimthoburn/480e5f58b6bb43e2f1dde010951d40fe to your computer and use it in GitHub Desktop.
Save jimthoburn/480e5f58b6bb43e2f1dde010951d40fe to your computer and use it in GitHub Desktop.
Find the closest ancestor HTML element that matches a tag name
function closest(element, tagName) {
// If the element is the target
if (element.nodeName.toLowerCase() === tagName) return element;
var ancestor = element;
while ((ancestor = ancestor.parentElement) && ancestor.nodeName && ancestor.nodeName.toLowerCase() !== tagName);
if (ancestor && ancestor.nodeName && ancestor.nodeName.toLowerCase() === tagName) {
return ancestor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment