当前位置:网站首页>How JS correctly clears all child elements under an element
How JS correctly clears all child elements under an element
2022-06-30 19:24:00 【JA+】
The following code , Deleting child nodes through traversal can cause problems
const userList = document.getElementById('userList');
for (let i = 0; i < userList.children.length; i++) {
const element = userList.children[i];
element.remove();// userList.removeChild(element);
}It seems very intuitive .
in fact ,
call element.remove() or parentNode.removeChild(element) After deleting this element .
Original array (HTMLCollection) The size has changed !
This results in incomplete deletion of child elements .
because element.children The value of is HTMLCollection (MDN) object , Is a class array object . You can't traverse and delete the array .
So when you delete all the child elements , Each traversal HTMLCollection Delete the first value of the object .
Code
let ele;
while ((ele = userList.children.item(0))) {
ele.remove();
}
// or
while ((ele = userList.firstChild)) {
ele.remove();
}Use here HTMLCollection.item() To get the first 1 Elements . You can also use an array to get .element.children[0]
Now that you get the first element , There's a simpler way element.firstChild. The same goes for the last element element.lastChild ( This is also the code used by many schemes on the Internet )
firstChild / lastChild The return is Node type , Use firstElementChild 、lastElementChild Come back to Element type .
as for Node and Element What's the difference , Please search by yourself .
PS
This is why our contemporary front-end relies too much on the front-end framework for operation dom, And the original js Knowledge loopholes .
边栏推荐
猜你喜欢

熵-条件熵-联合熵-互信息-交叉熵

20220607跌破建议零售价,GPU市场正全面走向供过于求...

MySQL transaction concurrency and mvcc mechanism

Huaxing Securities: kitex practice under the original hybrid Cloud Architecture

Entry node of link in linked list - linked list topic

Unlimited cloud "vision" innovation | the 2022 Alibaba cloud live summit was officially launched

年复一年,为什么打破数据孤岛还是企业发展的首要任务

openGauss数据库源码解析系列文章—— 密态等值查询技术详解(上)

Pyth Solana is a bridge connecting reality on the chain

美国服务器租用和托管服务哪个好?
随机推荐
JS 如何正确清除一个元素下的所有子元素
企业选型作业上常犯的一个错误
Unity technical manual - preliminary performance optimization
「杂谈」如何改善数据分析工作中的三大被动局面
「经验」爬虫在工作中的实战应用『理论篇』
MySQL recursion
VS 常用的快捷键指令
Kubernetes----Pod配置容器启动命令
Can go struct in go question bank · 15 be compared?
小小笔记-整型提升(C语言)
Iris, the web framework of go
Nodejs installation and introduction
如何使用物联网低代码平台进行服务管理?
Unlimited cloud "vision" innovation | the 2022 Alibaba cloud live summit was officially launched
基于UDP协议设计的大文件传输软件
链表中环的入口结点-链表专题
DTD modeling
美国服务器租用和托管服务哪个好?
CTF flow analysis common questions (II) -usb flow
Where do the guests come from