Skip to content

Instantly share code, notes, and snippets.

@mayashavin
Last active February 4, 2018 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayashavin/31095e83bd641a92dc6725a10502b6b4 to your computer and use it in GitHub Desktop.
Save mayashavin/31095e83bd641a92dc6725a10502b6b4 to your computer and use it in GitHub Desktop.
//Given 2 identical DOM trees (but not equal) and one element of the first DOM tree,
//how would you find this element in the second DOM tree
//Questions to ask:
//1. Input: input node is inside DOM tree? Or need to check if it exists?
//2. Output node needs to be identical? Same tag?
//3. Are comments, texts considered as child nodes? - Yes, need to use childNodes, No, use children.
var sameLevelNodeIdenticalTrees = {
getIndexOf: function(nodeList, node){
return Array.prototype.indexOf.call(nodeList, node);
},
traverseByPath: function(path, treeRoot){
var foundNode = treeRoot;
for (var i = path.length - 1; i >= 0; i--){
var position = path[i];
if (foundNode && foundNode.children){
foundNode = foundNode.children[position];
}
else{
foundNode = undefined;
break;
}
}
return foundNode;
},
findPath: function(node, treeRoot){
var path = [];
if (node){
while (node && node !== treeRoot){
var parent = node.parentNode;
if (parent){
var index = this.getIndexOf(parent.children, node);
if (index !== -1){
path.push(index);
}
}
else{
if (treeRoot !== node){
path.length = 0;
break;
}
}
node = parent;
}
}
return path;
},
find: function(rootTreeA, nodeA, rootTreeB){
if (!rootTreeA || !nodeA || !rootTreeB) return undefined;
if (rootTreeA === nodeA) return rootTreeB;
var path = this.findPath(nodeA, rootTreeA), nodeB = undefined;
if (path && path.length > 0){
nodeB = this.traverseByPath(path, rootTreeB);
}
else{
throw Error('Node A is not in Tree A');
}
return nodeB;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment