DOM tree finding nodes
This is a pretty common interview question. Let's explore how we would solve it.
HTML
<div id="treeA" class="hello">
<span>Yo</span>
<span>rawr</span>
<div class="heading">
<div class="subheading">
Yoloo
</div>
<div id="node" class="subheading">
Sup
</div>
<div class="subheading">
rwar
</div>
<div class="subheading">
asffa
</div>
</div>
</div>
<div id="treeB" class="hello">
<span>Yo</span>
<span>rawr</span>
<div class="heading">
<div class="subheading">
asd
</div>
<div class="subheading">
Susadadp
</div>
<div class="subheading">
rwasdadadar
</div>
<div class="subheading">
asasdadadadffa
</div>
</div>
</div>
JavaScript
// Given a node from a DOM tree find the node in the same position from an identical DOM tree.
// Given two identical DOM tree structures, A and B, and a node from A, find the corresponding node in B.
// Questions we should ask: can we assume that there is only one of that specific node in the tree? If there are multiple what should we do?
// When we say "identical" what does this mean? Same levels of deepness I assume? Same tags?
// When it comes to finding the same position, does it mean we go through the same path based on tags or simply by levels?
function findDomNodeInTree(rootA, rootB, node) {
var pathToTake = findDomNodePath(rootA, node);
console.log(pathToTake);
var currentNode = rootB;
// DFS
while (currentNode && pathToTake.length != 0) {
var index = pathToTake.pop();
var children = Array.prototype.slice.call(currentNode.childNodes);
currentNode = children[index];
}
return currentNode;
}
function findDomNodePath(root, node) {
var current = node;
var path = [];
while (current.parentNode) {
if (current == root) {
return path;
} else {
var children = Array.prototype.slice.call(current.parentNode.childNodes);
console.log(children);
path.push(children.indexOf(current));
current = current.parentNode;
}
}
}
var domTreeA = document.getElementById('treeA');
var domTreeB = document.getElementById('treeB');
var node = document.getElementById('node');
console.log(findDomNodeInTree(domTreeA, domTreeB, node));