DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 29

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
}
Enter fullscreen mode Exit fullscreen mode

Start from both ends. If the current node in A matches the target, return the same position in B

if(rootA === target) return B;
Enter fullscreen mode Exit fullscreen mode

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;
  }
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)