假设以下标记:
<div id="outterParent">
<div id="innerParent">
<div class="children"></div>
<div class="children"></div>
<div class="children"></div>
</div>
</div>
就安全性(避免内存泄漏)和性能而言,这样做可以吗:
var outterParent = document.getElementById("outterParent");
var innerParent = document.getElementById("innerParent");
outterParent.removeChild(innerParent);
outterParent = innerParent = null;
...或者最好在删除 #innerParent
之前删除每个 .children
元素,如下所示:
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;
最佳答案
这要看情况。如果您在某处引用了子级,并且不将其删除,则无法对父级进行垃圾收集。
var child = document.querySelector('children');
document.getElementById("innerParent").remove();
child.parentNode; // #innerParent -> it can't be garbage collected
那么最好取消子引用,或者删除子引用:
var child = document.querySelector('children');
document.getElementById("innerParent").remove();
child.remove();
child.parentNode; // null -> #innerParent might be garbage collected
关于javascript - 与 child 一起最安全、最高效地去除元件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37094382/