[javascript] How to empty the content of a div

Does someone know how to empty the content of a div (without destroying it) in JavaScript?

Thanks,

Bruno

This question is related to javascript html

The answer is


If your div looks like this:

<div id="MyDiv">content in here</div>

Then this Javascript:

document.getElementById("MyDiv").innerHTML = "";

will make it look like this:

<div id="MyDiv"></div>


If by saying without destroying it, you mean to a keep a reference to the children, you can do:

var oldChildren = [];

while(element.hasChildNodes()) {
    oldChildren.push(element.removeChild(element.firstChild));
}

Regarding the original tagging (html css) of your question:

You cannot remove content with CSS. You could only hide it. E.g. you can hide all children of a certain node with:

#someID > * {
    display: none;
}

This doesn't work in IE6 though (but you could use #someID *).


This method works best to me:

Element.prototype.remove = function() {
    this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
    for(var i = this.length - 1; i >= 0; i--) {
        if(this[i] && this[i].parentElement) {
            this[i].parentElement.removeChild(this[i]);
        }
    }
}

To use it we can deploy like this:

document.getElementsByID('DIV_Id').remove();

or

document.getElementsByClassName('DIV_Class').remove();

In jQuery it would be as simple as $('#yourDivID').empty()

See the documentation.


An alternative way to do it is:

var div = document.getElementById('myDiv');
while(div.firstChild)
    div.removeChild(div.firstChild);

However, using document.getElementById('myDiv').innerHTML = ""; is faster.

See: Benchmark test

N.B.

Both methods preserve the div.


If you're using jQuery ...

$('div').html('');

or

$('div').empty();

you can .remove() each child:

const div = document.querySelector('div.my-div')
while(div.firstChild) div.firstChild.remove()