Skip to content

Home

Get parents until element matches selector

Finds all the ancestors of an element up until the element matched by the specified selector.

const getParentsUntil = (el, selector) => {
  let parents = [],
    _el = el.parentNode;
  while (_el && typeof _el.matches === 'function') {
    parents.unshift(_el);
    if (_el.matches(selector)) return parents;
    else _el = _el.parentNode;
  }
  return [];
};

getParentsUntil(document.querySelector('#home-link'), 'header');
// [header, nav, ul, li]

More like this

Start typing a keyphrase to see matching snippets.