Created
November 4, 2016 01:16
-
-
Save C-Rodg/f72d2743449bcb9ef5e62aae47835f27 to your computer and use it in GitHub Desktop.
This algorithm displays how you can locate the same node in another identical DOM tree.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Helper function to provide Array's indexOf method to DOM elements | |
function indexOf(arr, target) { | |
return Array.prototype.indexOf.call(arr, target); | |
} | |
// Get the path of the target node from Root A | |
function getPath(root, target) { | |
let current = target; | |
let path = []; | |
while(current !== root) { | |
path.unshift(indexOf(current.parentNode.childNodes, current)); | |
current = current.parentNode; | |
} | |
return path; | |
} | |
// Given a node path, map it to the node | |
function locateNodeFromPath(root, path) { | |
let target = root; | |
for(let i=0; i < path.length; i++) { | |
target = target.childNodes[path[i]]; | |
} | |
return target; | |
} | |
// Given two identical DOM trees and a target node, find the corresponding node | |
function getIdenticalNode(rootA, rootB, target){ | |
return locateNodeFromPath(rootB, getPath(rootA, target)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment