Javascript 删除所有子节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5402525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:02:29  来源:igfitidea点击:

Remove all child nodes

javascriptdojo

提问by Damir

How to remove all child nodes from <div id="test"></div>using Dojo or plain JavaScript?

如何从<div id="test"></div>使用 Dojo 或纯 JavaScript 中删除所有子节点?

回答by jordancpaul

While it is tempting to use el.innerHTML = "", and generally this works, a more correct approach would be:

虽然使用 el.innerHTML = "" 很诱人,而且通常这很有效,但更正确的方法是:

var el = document.getElementById('test');
while( el.hasChildNodes() ){
    el.removeChild(el.lastChild);
}

The reason for this is because IE really hates table manipulation with innerHTML (this is documented somewhere in MSDN).

这样做的原因是因为 IE 真的很讨厌使用 innerHTML 进行表格操作(这在 MSDN 中的某处有记录)。

EDIT: found the MSDN reference: http://msdn.microsoft.com/en-us/library/ms532998%28v=vs.85%29.aspx#TOM_Create

编辑:找到 MSDN 参考:http: //msdn.microsoft.com/en-us/library/ms532998%28v=vs.85%29.aspx#TOM_Create

回答by Stephen Chung

dojo.empty(node)will remove all children from the node, while keeping the node.

dojo.empty(node)将从节点中删除所有子节点,同时保留节点。

dojo.destroy(node)will remove all children from the node, and then removes the node from its parent as well.

dojo.destroy(node)将从节点中删除所有子节点,然后也从其父节点中删除节点。

回答by MiPnamic

hereis what you need:

是你需要的:

dojo.empty("someId");

dojo.empty("someId");

回答by Lalchand

document.getElementById('yourDivID').innerHTML="";

回答by baptx

You can use the W3C DOM property textContent as a replacement to Microsoft non-standard innerHTML/innerText, it's part of the DOM3 and supported by all major browsers including Internet Explorer since version 9 http://www.w3schools.com/jsref/prop_node_textcontent.asp

您可以使用 W3C DOM 属性 textContent 作为 Microsoft 非标准 innerHTML/innerText 的替代品,它是 DOM3 的一部分,并且从版本 9 开始得到所有主要浏览器的支持,包括 Internet Explorer http://www.w3schools.com/jsref/prop_node_textcontent .asp

Update: innerHTML/innerText is now part of HTML5 standard

更新:innerHTML/innerText 现在是 HTML5 标准的一部分