我们将详细研究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 了。











