如何在没有innerHTML =“”的情况下清除div的内容
我有一个由 JS 创建的 DOM 元素填充的 div,
我希望在 JS 函数重复时清除该 div,但是我听说使用 document.getElementById('elName').innerHTML = "";< /code> 不是一个好主意,
清除 div 内容的有效替代方法是什么?
I have a div that is filled by JS created DOM elements,
I want the div to be cleared upon the JS function repeating, however I have heard that using document.getElementById('elName').innerHTML = "";
is not a good idea,
What is a valid alternative to doing this to clear the div's contents?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果你有 jQuery 那么:
否则:
If you have jQuery then:
Otherwise:
原型方式是
Element.update()
例如:The Prototype way is
Element.update()
e.g.:如果您使用 jQuery,请查看
.empty()
方法 http:// /api.jquery.com/empty/If you're using jQuery have a look at the
.empty()
method http://api.jquery.com/empty/第2022章 答案:
使用
element.replaceChildren()
Doc< /a>
2022 Answer:
Use
element.replaceChildren()
Doc
您可以循环遍历其子项并删除,即。
或者,如果您使用的是 jQuery,请使用
.empty()
。这只是一个替代解决方案,
while
循环更加优雅。You could loop through its children and remove then, ie.
Or use
.empty()
if you are using jQuery.This is just an alternative solution, a
while
loop is much more elegant.您可以重新定义.innerHTML。在 Firefox 和 Chrome 中,使用 .innerHTML = "" 清除元素没有问题。在 IE 中,确实如此,因为任何子元素都会立即清除。在此示例中,“mydiv.innerHTML”通常会返回“undefined”。 (没有重新定义,即,自本文创建之日起,在 IE 11 中)
http://jsfiddle .net/DLLbc/9/
You can redefine .innerHTML. In Firefox and Chrome, it's not a problem to clear the elements with .innerHTML = "". In IE, it is, because any child elements are immediately cleared. In this example, "mydiv.innerHTML" would normally return "undefined". (without the redefine, that is, and in IE 11 as of the date of this post creation)
http://jsfiddle.net/DLLbc/9/