1

I am a situation where I have to clone an element, read it's attributes and other parsing functionality, but now since I don't do element.parentNode.appendChild(clonedElement) how do I delete this clone from memory?

var clonedElement = element.cloneNode();

// do some stuff with it

clonedElement = null; // is this good enough?

So yea, is the clonedElement = null; good enough to clear it from memory?

thednp
  • 4,401
  • 4
  • 33
  • 45

1 Answers1

3

If you want to remove the variable's reference to the DOM node, use

element = null;

Since Javascript is garbage collected, you don't need to delete objects themselves they will be removed when there is no way to refer to them anymore.

but

If a DOM element which is removed is reference-free (no references pointing to it) then yes the element itself is picked up by the garbage collector as well as any event handlers/listeners associated with it.

if there are references that still point to said element, the element and its event listeners are retained in memory.

var removeChilds = function (node) 
{
    var last;
    while (last = node.lastChild) node.removeChild(last);
};

removeChilds( element ) ;
element=null;