How to find an element in a DOM tree given 2 identical (in structure) DOM trees and one element of the first DOM tree.

Here is one approach you might take to find a corresponding node in a tree given two root nodes with an identical sub-structure and a sister node.

An interactive Stackblitz with the following code can be found here.

getCorrespondingNodeTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Inputs
// 2 root nodes
// 1 node in 1 DOM tree
// Output
// Other node in corresponding tree w/ identical tree structure
function getChildren(node) {
return Array.from(node.childNodes);
}
function getPathFromNode(node, root) {
const path = [];
while (node !== root && node && node.parentNode) {
const index = getChildren(node.parentNode).findIndex(el => el === node);
path.push(index);
node = node.parentNode;
}
return path.reverse();
}
function getCorrespondingNode(node, root1, root2) {
const path = getPathFromNode(node, root1);
let current = root2;
path.forEach(index => {
current = current.childNodes[index];
})
return current;
}
const root1 = document.getElementById('root1');
const root2 = document.getElementById('root2');
const node1 = document.getElementById('node1');
const node2 = document.getElementById('node2');
console.log(getCorrespondingNode(node1, root1, root2) === node2); // true
console.log(getCorrespondingNode(node2, root2, root1) === node1) // true