Skip to content

Instantly share code, notes, and snippets.

@jkarttunen
Last active April 12, 2020 06:54
Show Gist options
  • Save jkarttunen/bda8afd3884f9bb3d543e1ef899402e6 to your computer and use it in GitHub Desktop.
Save jkarttunen/bda8afd3884f9bb3d543e1ef899402e6 to your computer and use it in GitHub Desktop.
Find parent tag
/**
* 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