返回从文档根到给定元素的元素的所有祖先元素。

  • 使用 Node.parentNodewhile 循环向上移动元素的祖先树。

  • 使用 Array.prototype.unshift() 将每个新祖先添加到数组的开头。

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

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