Javascript 如何清空div的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5744233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to empty the content of a div
提问by Bruno
Does someone know how to empty the content of a div (without destroying it) in JavaScript?
有人知道如何在 JavaScript 中清空 div 的内容(而不破坏它)吗?
Thanks,
谢谢,
Bruno
布鲁诺
回答by Zach Rattner
If your div looks like this:
如果您的 div 如下所示:
<div id="MyDiv">content in here</div>
<div id="MyDiv">content in here</div>
Then this Javascript:
然后这个Javascript:
document.getElementById("MyDiv").innerHTML = "";
document.getElementById("MyDiv").innerHTML = "";
will make it look like this:
将使它看起来像这样:
<div id="MyDiv"></div>
<div id="MyDiv"></div>
回答by ezmilhouse
If you're using jQuery ...
如果您使用的是 jQuery ...
$('div').html('');
or
或者
$('div').empty();
回答by Dan Bray
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.
但是,使用document.getElementById('myDiv').innerHTML = "";
速度更快。
See: Benchmark test
请参阅:基准测试
N.B.
NB
Both methods preserve the div.
这两种方法都保留了 div。
回答by Felix Kling
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:
关于html css
您问题的原始标记 ( ):
You cannot remove content with CSS. You could only hide it. E.g. you can hide all children of a certain node with:
您无法使用 CSS 删除内容。你只能隐藏它。例如,您可以使用以下命令隐藏某个节点的所有子节点:
#someID > * {
display: none;
}
This doesn't work in IE6 though (but you could use #someID *
).
虽然这在 IE6 中不起作用(但您可以使用#someID *
)。
回答by Jan Zyka
In jQuery it would be as simple as $('#yourDivID').empty()
在 jQuery 中,它会像 $('#yourDivID').empty()
See the documentation.
请参阅文档。
回答by Chetabahana
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();
回答by Yukulélé
you can .remove()
each child:
你可以.remove()
每个孩子:
const div = document.querySelector('div.my-div')
while(div.firstChild) div.firstChild.remove()