How to remove an item that is not in the DOM?

var paragraphElement = document.createElement('p'); 

paragraphElement not in the DOM. How to remove it? I know I can use removeChild if it is in the DOM. I do not want to add paragraphElement to the DOM and then delete it. Any solution?

Thanks.

+4
source share
2 answers

If the object is no longer referenced, it will be marked for garbage collection. Therefore, when you leave a context where p is valid and the element is not referenced in any other way, garbage collection frees up memory whenever it works further. How garbage collection is achieved depends on the JavaScript engine.

You can also assign p new value without reference, for example 0 , or use p = null . Note that .removeChild will not only remove the child from memory from the DOM, but will free it for garbage collection if there is no other link to this node.

For more information, check MDN: Memory Management .

+6
source

If it's not in the DOM, then all you have to do is clear any JS links from it, and the garbage collector will delete it for you. This is essentially no different from a javascript object or javascript array. If you clear any links to it, the garbage collector will clear it.

So, if you create it like this:

 var paragraphElement = document.createElement('p'); 

Then all you have to do to get rid of it is clear that the link:

 var paragraphElement = null; 

Without reference to the javascript element, the garbage collector will remove it.

+1
source

All Articles