DOM – getting the path of a node

Hi, this post have the code solution of how to obtain the path of a node to get to the root node.

So, the problem is:

Given a root element and node element – return the path that the node element need to get to root element

So our DOM tree will be like this:

The HTML of that DOM tree is:

<!DOCTYPE html>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>DOM tree</title>
  <div id="rootA">

        <div id="nodeA"></div>

  <script src="getPath.js"></script>

Nice then our Javascript solution is:

// Getting the root element
const root = document.getElementById('rootA');

// Getting the node element
const node = document.getElementById('nodeA');

// Function to getPath
function getPath(root, node) { // receiving a root element and a node element
    const path = []; // To save the path of the node element that need to get to the root element

    // Starting to get the path from bottom (nodeA) to top (rootA)
    while (node !== root) {
        // Because we are going to start from the node element to the top then we need to know wich is the parent element of the node
        const parent = node.parentElement; // getting the parent element of the node element 

        const childrens = Array.from(parent.children); // Getting the childrens of the actual parent node in an Array (not in a HTMLCollection)
        const nodeIndex = childrens.indexOf(node); // Check if the actual node is in the childrens array, if yes - then get the position where the node element was founded

        path.push(nodeIndex); // Saving the position that the node element was founded into the path array

        node = parent; // Now we're moving up so now the current node will be the parent node...and the process will be repeated

    return path;

// Executing the function
let path = getPath(root, node);

// Printing final path in the browser
console.log('path ---->', path);


By Cristina Rojas.