Identical DOM TreesLoading saved progress…

identicalDomTrees

Write a function that decides whether two DOM nodes describe the same tree. Two trees are structurally equal when they have the same node type and, recursively, the same tag, the same attributes, and the same children in the same order. This is what the browser's built-in Node.isEqualNode does — you're reimplementing it from scratch so you understand exactly which differences count and which don't.

Signature

function identicalDomTrees(a: Node, b: Node): boolean;

Returns true when the two nodes are structurally equal, false otherwise. The two nodes themselves do not need to be the same object — two separately built trees that look identical must return true.

Examples

const a = document.createElement('div');
a.innerHTML = '<p class="x">hi</p>';
const b = document.createElement('div');
b.innerHTML = '<p class="x">hi</p>';

identicalDomTrees(a, b); // → true  (same tag, attrs, and text)
const c = document.createElement('div');
c.innerHTML = '<p class="x">hi</p>';
const d = document.createElement('div');
d.innerHTML = '<p class="y">hi</p>'; // attribute value differs

identicalDomTrees(c, d); // → false

Notes

  • Node type first. A text node and an element node are never equal, even if their text matches. Compare nodeType before anything else.
  • Elements are equal when they share a tagName, the same set of attributes (name and value), and the same children compared pairwise in order, recursively.
  • Attributes are a set, not a list. id="a" class="b" equals class="b" id="a" — order does not matter, but every name must map to the same value.
  • Text nodes are equal when their nodeValue (the text itself) matches.
  • Children must line up. Same number of children, and the i-th child of a must equal the i-th child of b. Different counts or a different order means not equal.
  • No shortcuts via HTML strings. Comparing serialized markup (outerHTML) is not the same thing — it is sensitive to attribute order and whitespace that should not affect the answer.
Loading editor…