DEV Community

Shweta Kale
Shweta Kale

Posted on • Edited on

DOM question #3 Distance between two DOM

Find the distance (number of edges) between two DOM elements.

Image description

We can get distance between given 2 nodes by calculating LCA and then adding the distance between LCA to these two nodes.

So we can write code as

const getParentList = (node)=>{
   const parentList = [node];
let tempNode = node;
  while(tempNode.parentElement){
    parentList.push(tempNode.parentElement);
      tempNode = tempNode.parentElement;
  }

return parentList;
}

const LCA = (node1, node2)=>{
  const parentList1 = getParentList(node1);
  const parentList2 = getParentList(node2);

   for(let i=0; i<parentList1.length; i++){
       const index2 = parentList2.findIndex(item=> item === parentList1[i]);
       if(index2!==-1){
          return index2 + i;
       }
   }
return -1;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more