简体   繁体   English

删除所有子节点

[英]Remove all child nodes

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

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

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)将从dojo.destroy(node)删除所有子节点,然后从其父节点中删除该节点。

是你需要的:

dojo.empty("someId");

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

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标准的一部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM