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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…