From d9812f8e6b3ab8d0621de68d51bdb22c53c31357 Mon Sep 17 00:00:00 2001 From: Andy Blum Date: Wed, 14 Oct 2020 14:18:20 -0400 Subject: [PATCH] add getDomPath.md --- snippets/getDomPath.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 snippets/getDomPath.md diff --git a/snippets/getDomPath.md b/snippets/getDomPath.md new file mode 100644 index 000000000..c9291ac6e --- /dev/null +++ b/snippets/getDomPath.md @@ -0,0 +1,26 @@ +--- +title: getDomPath +tags: 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 + +```js +const getDomPath = (el) => + { + const path = []; + while (el) { + path.unshift(el); + el = el.parentElement; + } + return path; + } +``` + +```js +functionName(document.querySelector('nav')); // [html, body, header, nav] +```