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<parentList1.length; i++){
const index2 = parentList2.findIndex(item=> item === parentList1[i]);
if(index2!==-1){
return index2 + i;
}
}
return -1;
}
Top comments (0)