Files
30-seconds-of-code/snippets/getAncestors.md
Isabelle Viktoria Maciohsek 920a0c390b Update snippet descriptions
2020-10-19 22:49:51 +03:00

565 B

title, tags
title tags
getAncestors browser,beginner

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

  • Use a Node.parentNode and a while loop to move up the ancestor tree of the element.
  • Use Array.prototype.unshift() to add each new ancestor to the start of the array.
const getAncestors = el => {
  let ancestors = [];
  while (el) {
    ancestors.unshift(el);
    el = el.parentNode;
  }
  return ancestors;
};
getAncestors(document.querySelector('nav')); 
// [document, html, body, header, nav]