From 95071a86343103cd728080c8b5d4f5bd035aa9d0 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Thu, 15 Oct 2020 09:28:34 +0300 Subject: [PATCH] Update and rename getDomPath.md to getAncestors.md --- snippets/getAncestors.md | 24 ++++++++++++++++++++++++ snippets/getDomPath.md | 26 -------------------------- 2 files changed, 24 insertions(+), 26 deletions(-) create mode 100644 snippets/getAncestors.md delete mode 100644 snippets/getDomPath.md diff --git a/snippets/getAncestors.md b/snippets/getAncestors.md new file mode 100644 index 000000000..f962c47e6 --- /dev/null +++ b/snippets/getAncestors.md @@ -0,0 +1,24 @@ +--- +title: getAncestors +tags: browser,beginner +--- + +Returns all the ancestors of an element from the document root to the given element. + +- Use a `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. + +```js +const getAncestors = el => { + let ancestors = []; + while (el) { + ancestors.unshift(el); + el = el.parentNode; + } + return ancestors; +}; +``` + +```js +getAncestors(document.querySelector('nav')); // [document, html, body, header, nav] +``` diff --git a/snippets/getDomPath.md b/snippets/getDomPath.md deleted file mode 100644 index c9291ac6e..000000000 --- a/snippets/getDomPath.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -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] -```