Files
30-seconds-of-code/snippets/getDomPath.md
2020-10-14 14:18:20 -04:00

556 B

title, tags
title tags
getDomPath javascript, browser

Returns an array of an element's ancestors ordered from the document root to the given element

  • Pass an element to the function, returns an array of elements
  • Returned array has given element and all ancestor elements in order from document root downward
const getDomPath = (el) =>
  {
    const path = [];
    while (el) {
      path.unshift(el);
      el = el.parentElement;
    }
    return path;
  }
functionName(document.querySelector('nav')); // [html, body, header, nav]