JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

HTML

<!-- Tree 1 -->
<div id="tree1">
  <div>
    <p class="some-class">Node to Find</p>
    <div>
      <span>Other Content</span>
    </div>
  </div>
</div>
<hr/>
<!-- Tree 2 (Identical to Tree 1) -->
<div id="tree2">
  <div>
    <p class="some-class">Node to Find</p>
    <div>
      <span>Other Content</span>
    </div>
  </div>
</div>

JavaScript

// Place your provided code here

  function init(){
    let root1 = document.getElementById('root1');
    let node1 = document.getElementById('node1');
    let root2 = document.getElementById('root2');
    let node2 = document.getElementById('node2'); // Define node2

    let findNode = domTraversal(root1, root2, node1, node2);

    console.log(findNode === node2);
  }

  function domTraversal(root1, root2, node1, node2){
    const path = getPath(root1, node1);
    return checkSimilarDom(root2, path, node2);
  }

  function getPath(root1, node1){
    let path = [];
    let currentNode = node1;

    while(currentNode !== root1 && currentNode && currentNode.parentNode ){
      let index = [...currentNode.parentNode.childNodes];
      index = index.indexOf(currentNode);
      path.push(index);
      currentNode = currentNode.parentNode;
    }
    return path;
  }

  function checkSimilarDom(root, path, node2){
    let arr = root;
    while(path.length){
      arr = [...arr.childNodes][path.pop()];        
    }
    return arr;
  }

  init();