frontend-challenges icon indicating copy to clipboard operation
frontend-challenges copied to clipboard

486 - Find Corresponding Node - javascript

Open jsartisan opened this issue 2 months ago • 0 comments

index.js

/**
 * Find corresponding node in two identical DOM trees.
 * @param {Node} rootA - Root of first tree
 * @param {Node} rootB - Root of second tree  
 * @param {Node} target - Target node in tree A
 * @returns {Node|null} Corresponding node in tree B
 */
function findCorrespondingNode(rootA, rootB, target) {
  if (target === rootA) return rootB;

  if (!target.parentElement) return null;

  const rootAWalker = document.createTreeWalker(rootA, NodeFilter.SHOW_ELEMENT);
  const rootBWalker = document.createTreeWalker(rootB, NodeFilter.SHOW_ELEMENT);

  let currentNodes = [rootAWalker.currentNode, rootBWalker.currentNode];

   while (currentNodes[0] !== target) {
    currentNodes = [rootAWalker.nextNode(), rootBWalker.nextNode()];
  }

  return currentNodes[1];
}

export { findCorrespondingNode };

jsartisan avatar Sep 27 '25 06:09 jsartisan