Node.parentNode
and a while
loop to move up the ancestor tree of the element.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]
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️