Created
September 8, 2016 01:24
-
-
Save jimthoburn/480e5f58b6bb43e2f1dde010951d40fe to your computer and use it in GitHub Desktop.
Find the closest ancestor HTML element that matches a tag name
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
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