Search code examples
javascriptdomremovechild

How can I remove an element that is not in the DOM?


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.


Solution

  • 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.