Skip to content

Instantly share code, notes, and snippets.

@jgoslow
Created August 13, 2022 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgoslow/68b5ea73ef34d4617ff1ede18c5c6b2b to your computer and use it in GitHub Desktop.
Save jgoslow/68b5ea73ef34d4617ff1ede18c5c6b2b to your computer and use it in GitHub Desktop.
Ancestor Selection JS Helper Functions
function getAncestorByAttribute(elem, attribute) {
if (elem.parentElement === null) {
return false;
} else if (elem.hasAttribute(attribute)) {
return elem;
} else {
return getAncestorByAttribute(elem.parentElement, attribute);
}
}
/**
* Ancestor Selection Helpers
*/
function getAncestorByClass(elem, selector) {
if (elem.parentElement === null) {
return false;
} else if (elem.classList.contains(selector)) {
return elem;
} else {
return getAncestorByClass(elem.parentElement, selector);
}
}
function getAncestorByTag(elem, tag) {
if (elem.parentElement === null) {
return false;
} else if (elem.tagName.toLowerCase() === tag.toLowerCase()) {
return elem;
} else {
return getAncestorByTag(elem.parentElement, tag);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment