How can I find an element's ancestor that is closest up the tree that has a particular class, in pure JavaScript? For example, in a tree like so:
<div class="far ancestor">
<div class="near ancestor">
<p>Where am I?</p>
</div>
</div>
Then I want div.near.ancestor
if I try this on the p
and search for ancestor
.
Best Answer
Update: Now supported in most major browsers
Note that this can match selectors, not just classes
https://developer.mozilla.org/en-US/docs/Web/API/Element.closest
For legacy browsers that do not support
closest()
but havematches()
one can build selector-matching similar to @rvighne's class matching: