简体   繁体   中英

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

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 you're using jQuery ...

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

or

$('div').empty();

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

NB

Both methods preserve the 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. Eg 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 * ).

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

See the documentation .

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

you can .remove() each child:

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

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 = "";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM