Categories
interview

Find Identical Node in DOM Tree

<!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"></div>
        <div></div>
      </div>
    </div>
  </div>
</body>
</html>
const rootA = document.getElementById("rootA");
const rootB = document.getElementById("rootB");
const nodeA = document.getElementById("nodeA");
const nodeB = document.getElementById("nodeB");

const path = [];
const findPath = () => {
  let currNode = nodeA;
  while (currNode !== rootA) {
    path.push(Array.from(currNode.parentElement.children).indexOf(currNode));
    currNode = currNode.parentElement;
  }
};

const findB = () => {
  let currNode = rootB;
  while (path.length > 0) {
    currNode = currNode.children[path.pop()];
  }
  console.log(currNode, currNode === nodeB);
};

findPath();
findB();