according to mdn documentation the method removeChild
removes a node from the DOM but it still resides in memory.
My problem is that I want to delete it from memory as well.
I've tried with the delete
operator but the object is still there...
myCanvas.parentElement.removeChild(myCanvas); // myCanvas actually removed from DOM
delete myCanvas; // false. does nothing
alert(myCanvas); // shows HTMLCanvasElement instead of undefined
The removed child node still exists in memory, but is no longer part of the DOM. You may reuse the removed node later in your code, via the oldChild object reference. ie event listeners might get removed, but node still exists in memory. You're only adding confusion - jQuery does nothing that with handlers that simple removeChild wouldn't.
Remove the class attribute node from the first <h1> element: The removeAttributeNode () method removes an attribute from an element. The removeAttributeNode () method returns an Attribute object. The removeAttribute () method removes an attribute, and does not have a return value.
If a DOM Element is removed, are its listeners removed from memory too? 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.
the .remove () method takes elements out of the DOM. Use .remove () when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach () instead.
Read http://perfectionkills.com/understanding-delete/. The delete operator is not for variables (that's why it returns false
).
If you want to remove the variable's reference to the DOM node, use
myCanvas = null;
to overwrite the value. Usually you never need to do this, because the garbage collector of JS does all the work for you.
Just assign another value to myCanvas
variable (like null
) so that no more variables reference the canvas element. Garbage Collection will do the rest.
Of course, there is no guarantee. This assumes that there are no other variables referencing the element as well. Otherwise, if there are other variables, objects etc. that still reference that canvas element, then it's not removed from memory at all. This gets harder to remove if there are closures that contain the references to the element but have no way to dereference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With