Skip to content

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.

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
}
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
}

Storing DOM nodes in component state “for later” often causes this. Prefer storing data, not elements.

Live demo: detached DOM nodes

Nodes are removed from the document but kept in a JS array.

— MBPeak: — MB