获取祖先元素

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

  • 使用 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]
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 14:00
不想多说了,什么逆天HR,还要教我礼貌😂
机械打工仔:这不纯傻卵吗,他还操心上别人老板了
投递BOSS直聘等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务