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

paragraphElement is not in the DOM. How can I remove it? I know I can use removeChild if it's in the DOM. I don't tend to add paragraphElement to the DOM and then remove it. Any solution?

Thank you.

weilou
  • 4,419
  • 10
  • 43
  • 56

2 Answers2

6

If an object isn't referenced anymore it will be marked for the garbage collection. So when you leave the context where p is valid and the element isn't referenced in any other way the garbage collection will free the memory whenever it will run next. How the garbage collection achieves this depends on the JavaScript engine.

You can also assign p a new non-reference value like 0, or use p = null. Notice that .removeChild won't remove the child from memory, only from the DOM, but will free it for garbage collection if there's no other reference on this node.

For more information, check MDN: Memory Management.

Zeta
  • 103,620
  • 13
  • 194
  • 236
  • The part that states *automatically destroyed* at least in my mind suggests it's freed at that moment, which I don't believe is true (correct me with references if I'm wrong). I think a more accurate statement is *freed for garbage collection*, as this is up to the browser's determination, not the action by the code itself. – Jared Farrish Aug 05 '12 at 15:53
1

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

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 reference:

var paragraphElement = null;

With no javascript references to the element, the garbage collector will remove it.

jfriend00
  • 683,504
  • 96
  • 985
  • 979