Bruno
Bruno

Reputation: 9017

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

Upvotes: 38

Views: 128410

Answers (8)

Yukulélé
Yukulélé

Reputation: 17052

you can use .replaceChildren() without argument:

const div = document.querySelector('div.my-div')
div.replaceChildren()

Upvotes: 0

You can empty your DOM using this:

const el = document.getElementById("MyDiv");
while (el.firstChild) {
  el.removeChild(el.firstChild);
}

This is supposed to be faster than the traditionally used method : document.getElementById("MyDiv").innerHTML = "";

Upvotes: 0

Dan Bray
Dan Bray

Reputation: 7822

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.

Upvotes: 9

eQ19
eQ19

Reputation: 10691

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();

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816292

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 *).

Upvotes: 4

Jan Zyka
Jan Zyka

Reputation: 17898

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

See the documentation.

Upvotes: 3

ezmilhouse
ezmilhouse

Reputation: 9121

If you're using jQuery ...

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

or

$('div').empty();

Upvotes: 12

Zach Rattner
Zach Rattner

Reputation: 21333

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>

Upvotes: 72

Related Questions