Does someone know how to empty the content of a div (without destroying it) in JavaScript?
Thanks,
Bruno
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
N.B.
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. 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 *
).
In jQuery it would be as simple as $('#yourDivID').empty()
See the documentation.
document.querySelector("#myDiv").InnerHTML = "";
–
Patience 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 use .replaceChildren()
without argument:
const div = document.querySelector('div.my-div')
div.replaceChildren()
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 = "";
© 2022 - 2024 — McMap. All rights reserved.