Some code keeps two copies of the same tree: a live preview and an editable draft, the page and a clone made for printing, the real DOM and a copy rendered off screen. When the user clicks a node in one copy, you need the node at the same position in the other. Ids do not help (a clone repeats them, and most nodes have none), and content does not either (five identical list items look the same). The position does: the path of child indexes from the root down to the node.
Write findMatchingNode(rootA, rootB, nodeA) in matching-node.js.
functionfindMatchingNode(rootA, rootB, nodeA) // returns a Node or null
rootA, rootB: the roots of two trees with the same structure (for example, rootB is rootA.cloneNode(true)).
nodeA: a node inside rootA (an element, a text node or a comment), or rootA itself.
Returns the node of rootB at the same position: the same child index at every level. Returns null when nodeA is not inside rootA, or when rootB has no node at that position.
consta= document.createElement("ul");a.innerHTML ="<li>same</li><li>same</li><li>same <b>bold</b></li>";constb= a.cloneNode(true);findMatchingNode(a, b, a.children[1]); // b.children[1]: the second <li> of bfindMatchingNode(a, b, a.querySelector("b").firstChild); // the text node "bold" in bfindMatchingNode(a, b, a); // b
JAVASCRIPT
findMatchingNode(a, b, document.body); // null: not inside ab.lastChild.remove();findMatchingNode(a, b, a.lastChild); // null: b has no third <li> now