DEV Community

Discussion on: Building a Simple Virtual DOM from Scratch

Collapse
 
maiermic profile image
Michael Maier

The version with

$parent.childNodes.forEach(($child, i) => {
    childPatches[i]($child as HTMLElement)
})
Enter fullscreen mode Exit fullscreen mode

does not work correctly if child nodes are removed, since live NodeList ($parent.childNodes) updates the collection automatically when the DOM changes (e.g. child is removed). Hence, forEach is not called for all (original) elements (child nodes). For example, if there are 3 child nodes and the first patch keeps the child and the second and third patch delete the child, then only the first and second patches are called. The third patch is not called, since the second patch removes the node, which removes it from $parent.childNodes.

It is fixed by the version that uses zip, since it copies the elements of $parent.childNodes into an Array, which is not automatically updated when the DOM changes.