如果我删除一个节点的 children 而没有先删除 *他们的* children,这些 grandchildren 会发生什么?
If I remove a node's children without removing *their* children first, what happens to these grandchildren?
我有一个容器节点,我在上面附加了一些标签,每个标签都有自己的 children:
var container = document.getElementById("my_container");
var my_label, some_element, other_element;
for (let i=0;i<some_number;i++) {
container.appendChild(my_label);
my_label.appendChild(some_element);
my_label.appendChild(other_element);
}
有时,我从容器中删除了 my_label 的所有实例,因此我可以将其他元素添加到容器中:
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
请注意,在这样做时,我不会删除 some_element 和 other_element 的任何实例。 my_label 的 children 会怎样?我的代码干净吗,还是我应该先删除 my_label 的所有 children 然后再删除 my_label?
提前感谢您的智慧!
What happens to these children of my_label?
没有。它们不再被任何脚本变量或 DOM 引用,因此它们将与标签一起被垃圾收集。
Is my code clean?
是的。
Should I first remove all children of my_label and then remove my_label?
不,您不需要递归遍历整个 DOM 子树并将所有内容分开。
我有一个容器节点,我在上面附加了一些标签,每个标签都有自己的 children:
var container = document.getElementById("my_container");
var my_label, some_element, other_element;
for (let i=0;i<some_number;i++) {
container.appendChild(my_label);
my_label.appendChild(some_element);
my_label.appendChild(other_element);
}
有时,我从容器中删除了 my_label 的所有实例,因此我可以将其他元素添加到容器中:
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
请注意,在这样做时,我不会删除 some_element 和 other_element 的任何实例。 my_label 的 children 会怎样?我的代码干净吗,还是我应该先删除 my_label 的所有 children 然后再删除 my_label?
提前感谢您的智慧!
What happens to these children of my_label?
没有。它们不再被任何脚本变量或 DOM 引用,因此它们将与标签一起被垃圾收集。
Is my code clean?
是的。
Should I first remove all children of my_label and then remove my_label?
不,您不需要递归遍历整个 DOM 子树并将所有内容分开。