Identical DOM Trees
JS Functions
Medium
20 min
dom
trees
recursion
Implement isSameTree(nodeA, nodeB). It returns true if the two DOM nodes are structurally identical and false otherwise. Do not use isEqualNode, outerHTML or innerHTML.
Two nodes are identical when:
- They have the same
nodeType. - Elements: they have the same tag name, the same set of attributes with the same values (attribute order doesn't matter), and identical child node lists.
- Text and comment nodes: they have the same
nodeValue. - Their child nodes are identical pairwise, in order. This includes text and comment nodes, so whitespace matters.
const a = document.createElement('div');
a.innerHTML = '<p class="x" id="1">Hi <b>there</b></p>';
const b = document.createElement('div');
b.innerHTML = '<p id="1" class="x">Hi <b>there</b></p>';
isSameTree(a, b); // true: attribute order doesn't matter
b.querySelector('b').textContent = 'you';
isSameTree(a, b); // false
Requirements
- Two references to the same node are identical.
- Compare attribute values exactly (
class="a b"is not the same asclass="b a"). - Must handle deep trees.
Follow-up
- Why is comparing
outerHTMLstrings a weaker check than it looks? - How does this relate to virtual DOM diffing?
- How would you return the path to the first difference instead of a boolean?
Spotted a mistake or a rights concern? Report an issue