Element destruction removes the DOM nodes created from a virtual DOM element and detaches their event listeners. The mechanism has three responsibilities: remove the element, recursively destroy its children, and clean up listeners and virtual-node references. section 4.2.2 section 4.3
Destroy an element in this order:
- Call the DOM element’s remove() method. section 4.2.2
- Call destroyDOM() for every child so nested text, elements, fragments, and components are destroyed recursively. section 4.2.2 section 11.1.3
- Use removeEventListener() with each stored event name and handler, then delete the listeners and el properties from the virtual node. section 4.2.2 section 11.1.3
Why full destruction can disrupt input
When application state changes, destroying and recreating the entire DOM replaces the focused input element. A TODO input therefore loses focus after every keystroke; later DOM-diffing work addresses this limitation. section 6.3.3
function removeElementNode(vdom) {
const { el, children, listeners } = vdom
el.remove()
children.forEach(destroyDOM)
if (listeners) {
removeEventListeners(listeners, el)
delete vdom.listeners
}
}
This implementation shows the complete element-destruction sequence: remove the node, recurse through children, and detach listeners before deleting stored listener data. section 4.2.2
