dom 删除所有子元素
Given an item in the DOM, use querySelector()
to identify it, like this:
给定DOM中的项目,请使用querySelector()
进行标识,如下所示:
const item = document.querySelector('#itemId')
then, to remove all its children elements, you have a few different solutions.
然后,要删除其所有子元素,您有几种不同的解决方案。
The fastest way looks like this:
最快的方法如下所示:
item.innerHTML = ''
Another solution that is suggested is this: create a loop, check if the firstChild
property is defined (the element has at least a child) and then remove it:
建议的另一种解决方案是:创建一个循环,检查是否已定义firstChild
属性(该元素至少具有一个孩子),然后将其删除:
const item = document.querySelector('#itemId')
while (item.firstChild) {
item.removeChild(item.firstChild)
}
The loop ends when all children are removed.
删除所有子级后,循环结束。
The first, in most performance benchmarks I checked, looks like being the fastest solution.
在我检查的大多数性能基准测试中,第一个似乎是最快的解决方案。
翻译自: https://flaviocopes.com/how-to-remove-children-element/
dom 删除所有子元素