Remove all child nodes

Damir picture Damir · Mar 23, 2011 · Viewed 34.2k times · Source

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

Answer

jordancpaul picture jordancpaul · Mar 23, 2011

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