The task is to find the corresponding element in B, given two identical DOM nodes A and B, with an element in A.
The boilerplate code
const findCorrespondingNode = (rootA, rootB, target) => {
// your code here
}
Start from both ends. If the current node in A matches the target, return the same position in B
if(rootA === target) return B;
If the node doesn't match the target, use a recursive function to search through the node.
for(let i = 0; i < rootA.children.length; i++) {
const found = findCorrespondingNode(rootA.children[i], rootB.children[i], target);
if(found) return found;
}
The final code is:
const findCorrespondingNode = (rootA, rootB, target) => {
// your code here
if(rootA === target) return rootB;
for(let i = 0; i < rootA.children.length; i++) {
const found = findCorrespondingNode(rootA.children[i], rootB.children[i], target);
if(found) return found;
}
return null;
}
That's all folks!
Top comments (0)