What is the difference between 'remove' and 'removeChild' method in javascript?

remove is a new function. It's a shortcut, making it simpler to remove an element without having to look for the parent node. It's unfortunately not available on old versions of Internet Explorer so, unless you don't want to support this browser, you'll have to use removeChild or use a polyfill.

The reason the child element is kept in memory is your code keeps a reference to it.

If you do

childDiv = null;

then there's no reference pointing to it and the browser can free the memory.


the node is not actually removed

The confusion might be because you might think removing an element means something like killing or destroying it.

enter image description here

But in fact, the concept of removal basically means breaking the relationship between a child and its parent. It's just a detachment.

enter image description here

Shouldn't I get an error while trying to insert an element which does not exist?

No, because it still exists.

How is remove different from removeChild?

remove only needs a reference to the child. removeChild needs a reference both to the parent and the child. The result is identical.

Is there any way to ensure that element is actually removed from memory?

No. You can only unreference it and hope that there is a garbage collector which will detect the object is not referenced and then will remove it.