How can Detached DOM elements cause memory leak in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

Detached Dom elements

Detached DOM elements are the elements which have been removed from the DOM but their memory is still retained because of JavaScript. This means that as long the element have a reference to any variable or an object anywhere, it does not garbage collected even after destroyed from the DOM.

DOM is like an double-linked tree which means a reference to a node in the tree will halt the entire tree from garbage collection.

Let's take an example of creating a DOM element in javascript. After creating the element destroy it but forget to delete the variable holding it. This scenario leads to a Detached DOM which has a reference not only to the particular DOM element but also to the entire tree.


In the following example, even after removed from the DOM, 'someText' will still have a reference in the global 'value' object.This is why it can't eliminated from garbage collector and continue to consume memory.This causes memory leak.

   var example = document.createElement("p"); = "someText";
   var value = {
    text: document.getElementById('someText')
   function createFun() {
      value.text.innerHTML = "Javascript is not Java";
   function deleteFun() {

Avoiding memory leak

To avoid memory leak, the best practice is to put var example inside listener, which makes it a local variable. When var example is deleted the path for the object will cutoff,allowing the garbage collector to release memory.

Updated on 30-Jul-2019 22:30:26