Last active
November 7, 2021 12:23
-
-
Save joshblack/81b61f33fdb6233c50eb to your computer and use it in GitHub Desktop.
Find the difference between two DOM NodeLists
This file contains hidden or 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
// Takes in two node lists, i.e: | |
// var orig = document.getElementsByTagName('*'); -> original DOM Tree | |
// var update = document.getElementsByTagName('*'); -> updated DOM Tree | |
// diff(orig, update); -> should return the affected nodes (deleted or added) | |
function diff(original, updated) { | |
// Create arrays from our two node lists. | |
var originalList = [].slice.call(original, 0), | |
updatedList = [].slice.call(updated, 0), | |
// Collection for our updated nodes | |
updatedNodes = [], | |
// Count to keep track of where we are looking at in the original DOM Tree | |
count = 0, | |
// Loop Counter | |
i; | |
// Go through all the nodes in our updated DOM Tree | |
for (i = 0; i < updatedList.length; i++) { | |
// Check for a mismatch in values | |
if (updatedList[i] !== originalList[count]) { | |
// Check if the value ever exists in our updated list | |
if (updatedList.indexOf(originalList[count]) !== -1) { | |
// The item exists somewhere in our updated list, we'll get there | |
// eventually. For now just push up the additions we have until we get | |
// to the node that exists in the original DOM Tree. | |
updatedNodes.push(updatedList[i]); | |
} else { | |
// The node does not exist in our updated list, it has been deleted. | |
// Need to increment our counter that we are using for original list | |
// and redo the current iteration against the new position. Also, add | |
// the deleted node to our list of affected nodes. | |
updatedNodes.push(originalList[count]); | |
count++; | |
i--; | |
} | |
} else { | |
// The value was found! Time to check the next ones. | |
count++; | |
} | |
} | |
return updatedNodes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment