Skip to content

Home

Get element ancestors

Returns all the ancestors of an element from the document root to the given element.

const getAncestors = el => {
  let ancestors = [];
  while (el) {
    ancestors.unshift(el);
    el = el.parentNode;
  }
  return ancestors;
};

getAncestors(document.querySelector('nav'));
// [document, html, body, header, nav]

More like this

Start typing a keyphrase to see matching snippets.