最安全,最高效的儿童元素去除

时间:2016-05-07 22:31:45

标签: javascript dom

假设以下标记:

<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;

...或者在删除.children之前移除每个#innerParent元素是否更好,如下所示:

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;

1 个答案:

答案 0 :(得分:1)

这取决于。如果您在某个地方提到了某个孩子,并且没有将其删除,那么父母就无法进行垃圾回收。

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