Return the path to the first differing node in two DOM trees
A server-rendering team wants to catch hydration bugs: after the client renders a component, a dev-only check compares the client’s DOM with the server’s DOM. A plain “they differ” is not very helpful in a large page, so the check reports where the first difference is.
Implement findDomDifference(a, b). It compares two DOM trees and returns the path to the first node where they differ, or null if they are the same.
findDomDifference(a, b) // => number[] | null
[] means the roots themselves differ. [2, 0] means “the root’s third child, then that node’s first child”.[...pathToParent, numberOfChildrenOfTheShorterNode].null when no difference is found.Do not modify either tree, and do not use isEqualNode or compare innerHTML strings.
const server = document.createElement('div');
server.innerHTML = `
<ul class="cart">
<li>Milk</li>
<!-- price loads later -->
<li>Eggs</li>
</ul>`;
const client = document.createElement('div');
client.innerHTML = '<ul class="cart"><li>Milk</li><li>Bread</li></ul>';
findDomDifference(server, client);
// => [0, 1, 0] (div > ul > second li > its text: "Eggs" vs "Bread")
const a = document.createElement('div');
a.innerHTML = '<input type="email" name="login">';
const b = document.createElement('div');
b.innerHTML = '<input name="login" type="email">';
findDomDifference(a, b); // => null (attribute order does not matter)
const short = document.createElement('ol');
short.innerHTML = '<li>a</li>';
const long = document.createElement('ol');
long.innerHTML = '<li>a</li><li>b</li>';
findDomDifference(short, long); // => [1] (the extra second li)
findDomDifference(document.createElement('section'), document.createElement('article'));
// => []