DOM tree finding nodes
This is a pretty common interview question. Let's explore how we would solve it.
by Prathameshsb
HTML
<div id="treeA" class="hello">
<span id="waste sapn 1">Yo A</span>
<span id="waste sapn 2">rawr A</span>
<d iv id="test1A" class="heading">
<div id="test2A" class="subheading">
Yoloo A
</div>
<div id="node" class="subheading">
Sup A
</div>
<div id="test3A" class="subheading">
rwar A
</div>
<div id="test4A" class="subheading">
asffa A
</div>
</div>
</div>
<br><hr><br>
<div id="treeB" class="hello">
<span id="waste sapn 1 b">Yo B</span>
<span id="waste sapn 2 b">rawr B</span>
<div id="test1B" class="heading">
<div id="test2B" class="subheading">
asd B
</div>
<div id="test3B" class="subheading">
Susadadp B
</div>
<div id="test4B" class="subheading">
rwasdadadar B
</div>
<div id="test5B" class="subheading">
asasdadadadffa B
</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();
console.log(index);
console.log(currentNode.childNodes);
var children = Array.prototype.slice.call(currentNode.childNodes);
console.log("Wait");
console.log(children);
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);
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));