Last active
April 30, 2024 03:15
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | |
}); | |
} |
Author
amitasaurus
commented
Apr 30, 2024
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