Last active
June 17, 2025 22:04
-
-
Save ferretwithaberet/3028fadf561797b913ddae9d156badb7 to your computer and use it in GitHub Desktop.
Get all ancestors of an element matching a selector in javascript
This file contains hidden or 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
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]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now with tail call optimization, if V8 decides we need TCO.