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

- 795,719
- 175
- 1,089
- 1,143

- 54,277
- 94
- 246
- 365
-
1possible duplicate of [Remove all the children DOM elements in div](http://stackoverflow.com/questions/683366/remove-all-the-children-dom-elements-in-div) – Felix Kling Mar 23 '11 at 08:25
-
This might help too: http://stackoverflow.com/questions/4401278/unregister-delete-all-child-nodes-of-a-div-tag-in-dojo – Felix Kling Mar 23 '11 at 08:26
5 Answers
While it is tempting to use el.innerHTML = "", and generally this works, a more correct approach would be:
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).
EDIT: found the MSDN reference: http://msdn.microsoft.com/en-us/library/ms532998%28v=vs.85%29.aspx#TOM_Create

- 2,954
- 1
- 18
- 27
dojo.empty(node)
will remove all children from the node, while keeping the node.
dojo.destroy(node)
will remove all children from the node, and then removes the node from its parent as well.

- 14,497
- 1
- 35
- 48
-
AMD - import dojo/dom-construct as domConstruct and then call domConstruct.empty(node) and domConstruct.destroy(node). – Deejers Jul 15 '14 at 13:15
-
however, potentially dangerous. This will not work with tables in IE – jordancpaul Mar 23 '11 at 08:33
-
no your not right i have tested with IE am able to remove all the child nodes from the Div. – Lalchand Mar 23 '11 at 08:39
-
3I suspect you have not tested this completely. As reported by microsoft's own documentation on [MSDN](http://msdn.microsoft.com/en-us/library/ms532998%28v=vs.85%29.aspx#TOM_Create): "_because of the specific structure required by tables, the innerText and innerHTML properties of the table and tr objects are read-only. To insert rows and cells, change the contents and attributes of the table, or resize table elements, you must use the DOM._" In other words, to rely on `el.innerHTML = ""` can be dangerous if you don't fully understand it. – jordancpaul Mar 23 '11 at 09:51
-
Since Internet Explorer 9 you can use W3C DOM property textContent working with all major browsers – baptx May 19 '12 at 16:30
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
Update: innerHTML/innerText is now part of HTML5 standard

- 3,428
- 6
- 33
- 42