Detached DOM Nodes
You'll learn how JavaScript references to removed DOM elements keep their memory alive, creating hidden memory leaks.
What Are Detached DOM Nodes?
When you remove a DOM element from the page (using methods like removeChild or remove), you might assume its memory gets freed immediately. Not so fast! If your JavaScript code still holds a reference to that element, it remains in memory even though it's no longer visible or part of the document tree. This is called a "detached" DOM node—disconnected from the DOM but still occupying memory.
Think of it like moving out of an apartment but keeping the keys. The apartment isn't available to new tenants (can't be garbage collected) because you still have access to it.
The Problem in Practice
The issue arises when you store DOM references in variables, closures, or data structures and forget about them after removing the elements:
let cachedElement = document.getElementById('temporary-dialog');
function closeDialog() {
cachedElement.remove(); // Removed from DOM, but...
// cachedElement still references it!
}
Even after closeDialog() runs, the entire dialog element—plus all its child nodes and event listeners—stays in memory because cachedElement keeps it reachable.
The Solution
Explicitly clear references when you're done:
let cachedElement = document.getElementById('temporary-dialog');
function closeDialog() {
cachedElement.remove();
cachedElement = null; // Now GC can reclaim it
}
This is especially important in single-page applications where DOM elements are frequently created and destroyed but the page never reloads.
Key Takeaway: Removing a DOM element from the page doesn't free its memory if JavaScript variables still reference it—always nullify those references to prevent detached node leaks.