Files
30-seconds-of-code/snippets/get-ancestors.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

677 B

title, tags, author, cover, firstSeen, lastUpdated
title tags author cover firstSeen lastUpdated
Get element ancestors browser chalarangelo interior-8 2020-10-15T09:28:34+03:00 2021-01-05T22:45:34+02:00

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

  • Use 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]