我们将详细研究nodelist和htmlcollection以及nodelist和htmlcollection。
首先,两者都有一个 length 属性,返回列表(集合)中的元素数量。
1.html集合
html dom 中的
htmlcollection 已上线; getelementsbyclassname() 或 getelementsbytagname() 返回一个实时 htmlcollection ,表示具有所有给定 类名称的所有子元素的类似数组的对象.
示例 :
nodelist and htmlcollection
- item-1
- item-2
- item-3
- item-4
- item-5
- item-6
- item-7
- item-8
- item-9
- item-10
- item-11
- item-12
登录后复制登录后复制
const selected = document.getelementsbyclassname("items")console.log(selected)
登录后复制
输出 :
立即学习“前端免费学习笔记(深入)”;
当底层文档更改时,htmlcollection 会自动更新。
让我们写一个示例 :
nodelist and htmlcollection
登录后复制登录后复制
const selected = document.getelementsbyclassname("card")console.log(selected)selected[0].innerhtml += `
登录后复制
输出 :
从输出中可以看出,当将新的 html 标签添加到具有卡片类的元素时,htmlcollection 会更新因为它是活动的
2. 节点列表
queryselectorall() 返回一个 static (非实时) nodelist 表示与指定组匹配的文档元素列表选择器。但是 childnodes 返回一个 live nodelist。
示例 :
nodelist and htmlcollection
- item-1
- item-2
- item-3
- item-4
- item-5
- item-6
- item-7
- item-8
- item-9
- item-10
- item-11
- item-12
登录后复制登录后复制
const selected = document.queryselectorall(".items")console.log(selected)
登录后复制
输出 :
当对底层文档进行更改时,queryselectorall() 返回的 nodelist 不会自动更新,因为 它是非活动的。
让我们写一个示例 :
nodelist and htmlcollection
登录后复制登录后复制
const selected = document.queryselectorall(".card")selected[0].innerhtml += `
登录后复制
输出 :
浏览器
控制台
从输出中可以看出,当将新的 html 标签添加到具有卡片类的元素时,浏览器会更新,但 nodelist 不会更新,因为 nodelist 不活动.
当底层文档发生更改时,childnodes 返回的 nodelist 会自动更新,因为它是活动的。
示例 :
nodelist and htmlcollection
登录后复制
const selected = document.querySelector(".card")selected.innerHTML += `
登录后复制
输出 :
从输出中可以看出,当一个新的 html 标签添加到具有卡片类的元素时,nodelist 会更新因为它是活动的。
结论
总之,htmlcollection 始终是一个实时集合。 nodelist 通常是静态集合。
我们检查了 nodelist 和 htmlcollection 是什么。现在您知道什么是 nodelist 和 htmlcollection 了。
以上就是NodeList 与 HTMLCollection:实时集合和静态集合之间的区别的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2657808.html