dom 删除所有子元素_如何从DOM元素中删除所有子级

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 删除所有子元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值