Find the closest ancestor element that has a specific class

Update: Now supported in most major browsers


Note that this can match selectors, not just classes

For legacy browsers that do not support closest() but have matches() one can build selector-matching similar to @rvighne’s class matching:

function findAncestor (el, sel) {
    while ((el = el.parentElement) && !((el.matches || el.matchesSelector).call(el,sel)));
    return el;

Leave a Comment