Detached DOM nodes
A DOM node is detached when it’s no longer in the document tree but JavaScript still references it. The entire subtree stays in memory.
flowchart LR doc[document tree] arr[detachedNodes array] el[div subtree] doc -. removed .-> el arr --> el
Modern browsers can sometimes collect detached nodes if only weak references remain — but if your code holds a strong reference, they leak.
Broken code
Section titled “Broken code”const cache = [];
function replacePanel(html) { const old = document.getElementById('panel'); const neu = document.createElement('div'); neu.innerHTML = html; old.replaceWith(neu); cache.push(old); // keeps old subtree alive}Fixed code
Section titled “Fixed code”function replacePanel(html) { const old = document.getElementById('panel'); const neu = document.createElement('div'); neu.innerHTML = html; old.replaceWith(neu); // let old go out of scope — no extra references}Framework angle
Section titled “Framework angle”Storing DOM nodes in component state “for later” often causes this. Prefer storing data, not elements.
Live demo
Section titled “Live demo”Live demo: detached DOM nodes
Nodes are removed from the document but kept in a JS array.
`performance.memory` is only available in Chromium-based browsers. Use Chrome for live heap readouts.