Skip to content

Instantly share code, notes, and snippets.

@std-microblock
Last active February 1, 2025 18:53
Show Gist options
  • Select an option

  • Save std-microblock/a91ec3cd588a2a0f336bb8c30ded81db to your computer and use it in GitHub Desktop.

Select an option

Save std-microblock/a91ec3cd588a2a0f336bb8c30ded81db to your computer and use it in GitHub Desktop.
diffEditHTML
function diffEditHTML(after, oldDOM) {
const newDOM = document.createElement('div');
newDOM.innerHTML = after;
const newChildNodes = [...newDOM.childNodes],
oldChildNodes = [...oldDOM.childNodes];
let diffStart = Number.POSITIVE_INFINITY;
for (let i = 0; i < Math.max(newChildNodes.length, oldChildNodes.length); i++) {
const newChildDom = newChildNodes[i], oldChildDom = oldChildNodes[i];
if (!!newChildDom && !!oldChildDom) {
if ((newChildDom.innerHTML && !oldChildDom.innerHTML) ||
(!newChildDom.innerHTML && oldChildDom.innerHTML) ||
newChildDom.innerHTML !== oldChildDom.innerHTML ||
newChildDom.textContent !== oldChildDom.textContent
) {
diffStart = i;
break;
}
} else {
diffStart = i;
break;
}
}
for (let i = diffStart; i < oldChildNodes.length; i++) oldDOM.removeChild(oldChildNodes[i])
for (let i = diffStart; i < newChildNodes.length; i++) {
oldDOM.appendChild(newChildNodes[i])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment