Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all child nodes

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

like image 645
Damir Avatar asked Mar 23 '11 08:03

Damir


2 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

like image 199
jordancpaul Avatar answered Sep 25 '22 12:09

jordancpaul


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.

like image 20
Stephen Chung Avatar answered Sep 23 '22 12:09

Stephen Chung