Menu

gitpiper

getAncestors javascript Code Snippet in 2024

browserbeginner

Last Updated: 24 March 2024

Returns all the ancestors of an element from the document root to the given element.

  • Use Node.parentNode and a while loop to move up the ancestor tree of the element.
  • Use 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]

javascript snippet similar to getAncestors For You in March 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️