0
点赞
收藏
分享

微信扫一扫

获取祖先元素

迪莉娅1979 2022-07-27 阅读 39

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

  • 使用​​Node.parentNode​​和 ​​while​​ 循环向上移动元素的祖先树。
  • 使用​​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]

举报

相关推荐

0 条评论