<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>DOM Traversal</title>
</head>
<body>
<div id="rootA">
<div>
<div></div>
</div>
<div></div>
<div>
<div>
<div id="nodeA"></div>
<div></div>
</div>
</div>
</div>
<div id="rootB">
<div>
<div></div>
</div>
<div></div>
<div>
<div>
<div id="nodeB">Node B</div>
<div></div>
</div>
</div>
</div>
</body>
</html>
const rootA = document.getElementById("rootA");
const rootB = document.getElementById("rootB");
const nodeA = document.getElementById("nodeA");
const path = [];
const findPath = () => {
let currNode = nodeA;
while (currNode !== rootA) {
path.push(
[...currNode.parentElement.children]
.indexOf(currNode)
);
currNode = currNode.parentElement;
}
};
const findB = () => {
let currNode = rootB;
while (path.length) {
currNode = currNode.children[path.pop()];
}
return currNode;
};
findPath();
console.log(findB().innerHTML); // Node B
Demo
Related