30秒学会 JavaScript 片段 · 2023年9月21日

30秒学会 JavaScript 片段 – Get element ancestors

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]

翻译自:https://www.30secondsofcode.org/js/s/get-ancestors