Last active
April 12, 2020 06:54
-
-
Save jkarttunen/bda8afd3884f9bb3d543e1ef899402e6 to your computer and use it in GitHub Desktop.
Find parent tag
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
/** | |
* Recursively find parents until matching tag has been found. | |
* Useful when observing clicks on elements with child elements, but you need to use data- attributes from parent. | |
* @param {HTMLElement} element - Element to find parent from. | |
* @param {string} tag - Parent tag to find. Eg. 'DIV' or 'H1' | |
**/ | |
function findParentTag(element, tag) { | |
const tagName = tag.toUpperCase(); | |
if (element.tagName === tagName) return element; | |
while (element.parentNode) { | |
element = element.parentNode; | |
if (element.tagName === tagName) return element; | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment