Skip to content

Instantly share code, notes, and snippets.

@amitasaurus
Last active April 30, 2024 03:15
Show Gist options
  • Save amitasaurus/3f2547b83405b3762d9db045556c2008 to your computer and use it in GitHub Desktop.
Save amitasaurus/3f2547b83405b3762d9db045556c2008 to your computer and use it in GitHub Desktop.
Implement a function identicalDOMTrees that checks if two DOM trees are identical or not.
export default function identicalDOMTrees(nodeA: Node, nodeB: Node): boolean {
//traversing two root nodes at the same time and compare them
if (nodeA.nodeType !== nodeB.nodeType) return false;
if (nodeA.nodeType === Node.TEXT_NODE)
return nodeA.textContent === nodeB.textContent;
// We can assume it's an element node from here on.
const elA = nodeA as Element;
const elB = nodeB as Element;
if (elA.tagName !== elB.tagName) return false;
if (elA.childNodes.length !== elB.childNodes.length) return false;
if (elA.attributes.length !== elB.attributes.length) return false;
const hasSameAttributes = elA
.getAttributeNames()
.every((attr) => elA.getAttribute(attr) === elB.getAttribute(attr));
if (!hasSameAttributes) return false;
return Array.from(elA.childNodes).every((child, index) => {
return identicalDOMTrees(child, elB.childNodes[index]);
});
}
@amitasaurus
Copy link
Author

const treeA = new DOMParser().parseFromString(
  `<div><span>Foo</span><p>Para</p></div>`,
  'text/html'
);
const treeB = new DOMParser().parseFromString(
  `<div><span>Foo</span><p>Para</p></div>`,
  'text/html'
);

const treeC = new DOMParser().parseFromString(
  `<div><span>Foo</span><p>Para</p></div>`,
  'text/html'
);
const treeD = new DOMParser().parseFromString(
  `<div><span>Bar</span><p>Para</p></div>`,
  'text/html'
);
console.log(identicalDOMTrees(treeA.body, treeB.body)); //true
console.log(identicalDOMTrees(treeC.body, treeD.body)); //false

@amitasaurus
Copy link
Author

Two DOM trees are considered identical if they are structurally similar, and the DOM nodes on one tree have the exact same attributes as the nodes on the same relative position on the other tree.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment