Skip to content

Instantly share code, notes, and snippets.

@ferretwithaberet
Last active June 17, 2025 22:04
Show Gist options
  • Save ferretwithaberet/3028fadf561797b913ddae9d156badb7 to your computer and use it in GitHub Desktop.
Save ferretwithaberet/3028fadf561797b913ddae9d156badb7 to your computer and use it in GitHub Desktop.
Get all ancestors of an element matching a selector in javascript
const allAncestors = (element, selector, acc = []) => {
if (!element.parentElement) return acc;
const ancestor = element.parentElement.closest(selector);
if (!ancestor) return acc;
return allAncestors(ancestor, selector, [ancestor, ...acc]);
}
@ferretwithaberet
Copy link
Author

Now with tail call optimization, if V8 decides we need TCO.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment