frontend-challenges
frontend-challenges copied to clipboard
486 - Find Corresponding Node - javascript
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 };