DOM question #3
Find the distance (number of edges) between two DOM elements. 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 item === parentList1[i]); if(index2!==-1){ return index2 + i; } } return -1; }

Find the distance (number of edges) between two DOM elements.
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 item === parentList1[i]);
if(index2!==-1){
return index2 + i;
}
}
return -1;
}