Skip to content

Latest commit

 

History

History
40 lines (23 loc) · 702 Bytes

getAncestors.md

File metadata and controls

40 lines (23 loc) · 702 Bytes
标题 标签
getAncestors(获取元素的祖先元素) browser(浏览器)

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

  • 使用 Node.parentNode 和 while 循环向上移动元素的祖先树。
  • 使用 Array.prototype.unshift() 将每个新祖先添加到数组的开头。
const getAncestors = el => {
    const ancestors = [];
    while(el){
        ancestors.unshift(el);
        el = el.parentNode;
    }
    return ancestors;
}

调用方式:

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

应用场景

<iframe src="codes/javascript/html/getAncestors.html"></iframe>