I have created an HTML page to understand how removing an element works.
Code:
<html>
<head>
<script>
var childDiv = null;
var parent1 = null;
var parent2 = null;
function init() {
childDiv = document.getElementById("child");
parent1 = document.getElementById("parent1");
parent2 = document.getElementById("parent2");
}
function rem() {
if (childDiv) {
childDiv.remove();
alert("child removed");
} else {
alert("child does not exist");
}
}
function remChild() {
if (childDiv){
if (parent1.children.length > 0) {
parent1.removeChild(childDiv);
alert("child unbound from parent");
} else {
alert("child exists but is not bound to parent");
}
} else {
alert("child does not exist");
}
}
function ins() {
if (childDiv) {
parent2.appendChild(childDiv);
alert("child inserted to another parent");
}
}
</script>
</head>
<body onload="init()">
<div id="parent1">
<div id="child"></div>
</div>
<div id="parent2"></div>
<button onclick="rem()">remove</button>
<button onclick="remChild()">removeChild</button>
<button onclick="ins()">insert</button>
</body>
</html>
Here I try to remove the 'child' div in two ways:
By calling 'remove' method on 'child' div
By calling 'removeChild' method on 'parent1' node
But in both the cases, the node is not actually removed. I can always insert 'child' div to 'parent2'.
I can understand that in second case, the 'child' is unbound from 'parent1' and not actually deleted. But in first case, is the 'child' not removed permanently?
Shouldn't I get an error while trying to insert an element which does not exist?
Please explain.
And if the element does exist even after calling 'remove' on element:
How is 'remove' different from 'removeChild'? As I see, both these methods just unbound child from parent, but element still occupies the memory.
Is there any way to ensure that element is actually removed from 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.
But in fact, the concept of removal basically means breaking the relationship between a child and its parent. It's just a detachment.
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 fromremoveChild
?
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.
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