How do I clear the contents of a div without innerHTML = "";

Myles Gray picture Myles Gray · Feb 20, 2011 · Viewed 68.8k times · Source

I have a div that is filled by JS created DOM elements,

I want the div to be cleared upon the JS function repeating, however I have heard that using document.getElementById('elName').innerHTML = ""; is not a good idea,

What is a valid alternative to doing this to clear the div's contents?

Answer

Alnitak picture Alnitak · Feb 20, 2011

If you have jQuery then:

$('#elName').empty();

Otherwise:

var node = document.getElementById('elName');
while (node.hasChildNodes()) {
    node.removeChild(node.firstChild);
}