Reputation: 1928
Assume the following markup:
<div id="outterParent">
<div id="innerParent">
<div class="children"></div>
<div class="children"></div>
<div class="children"></div>
</div>
</div>
In terms of safety (avoiding memory leaks) and performance, is it OK to do something like this:
var outterParent = document.getElementById("outterParent");
var innerParent = document.getElementById("innerParent");
outterParent.removeChild(innerParent);
outterParent = innerParent = null;
...or is it better to remove each .children
element prior to removing #innerParent
, like this:
var outterParent = document.getElementById("outterParent");
var innerParent = document.getElementById("innerParent");
var child;
while (innerParent.firstChild){
child = innerParent.firstChild;
innerParent.removeChild(child);
}
outterParent.removeChild(innerParent);
outterParent = innerParent = child = null;
Upvotes: 1
Views: 36
Reputation: 288580
It depends. If you have a reference to a child somewhere, and don't remove it, the parent can't be garbage collected.
var child = document.querySelector('children');
document.getElementById("innerParent").remove();
child.parentNode; // #innerParent -> it can't be garbage collected
So then it would be better to nullify the child reference, or remove the child:
var child = document.querySelector('children');
document.getElementById("innerParent").remove();
child.remove();
child.parentNode; // null -> #innerParent might be garbage collected
Upvotes: 1