Does removeChild really remove the item?

removeChild function really completely remove the node child? Or does it just remove the element that is a child of the specified node parameter? If it really does not delete the item, is there a way to completely remove the item?

+7
source share
4 answers

The removeChild method simply removes it from the parent. If this is a visible page element, it will be removed from the page.

But Javascript does contain garbage collection. This means that the node object itself will exist as long as any variable refers to it. This way you can assign a node variable, use removeChild to “trim” it from the parent node, and then paste or add it to some other node, thereby effectively moving it around the page.

The following code will remove the node and wait 10 seconds before re-adding it to the tree (and therefore to the page):

 var oldNode = someNode.removeChild(...); setTimeout(function () { document.documentElement.appendChild(oldNode); }, 10000); 

This means that the node object has not been deleted from memory, because theres still points to it with a variable (namely oldNode ).

Another case:

 var node = document.getElementById('test'); // ... do stuff node.parentElement.removeChild(node); // 'node' still exists, but has been removed from the page // ... do some more stuff node = document.getElementById('hello'); // The variable 'node' now points to something else; // this means the original node will be deleted from memory 

If, on the other hand, you do not reassign the remote node to another variable, you no longer need to access it (not through the document tree, since it was deleted from there, and not through the JS variable); therefore, Javascript will automatically clear it from memory:

 someNode.removeChild(...); 

Assigning a remote node variable to a variable, and then null (or something else) to this variable - as Mark B does in his answer - is completely unnecessary and, IMHO, stupid.

+14
source

This will completely remove the node:

 someNode.removeChild(...); 

This will remove the node from the DOM so that it is not visible, but save it so you can paste it in another location:

 oldNode = someNode.removeChild(...); 
+10
source

removeChild removes the element from dom, but it also returns from the function in case you do the removal to reinsert it in another place. You will have to kill this return value to really get rid of the remote node:

 oldNode = someNode.removeChild(...); oldNode = null; 
+1
source

If you want to really remove the dom element. removeChild is not enough. This is according to Steve Saunder, author of YSlow. You need to use delete

+1
source

All Articles