Reputation: 4617
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.
Upvotes: 4
Views: 193
Reputation: 707148
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.
Upvotes: 1
Reputation: 105876
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.
Upvotes: 6