HTMLCollection 长度
示例
文档中有多少个段落
let number = document.getElementsByTagName("p").length;
自己动手试一试 »
循环遍历类名为 "myclass" 的元素并改变它们的字体大小
const collection = document.getElementsByClassName("myclass");
for (let i = 0; i < collection.length; i++) {
collection[i].style.fontSize = "24px";
}
自己动手试一试 »
描述
length
属性返回 HTMLCollection 中元素的数量。
length
属性是只读的。
当您想遍历 HTMLCollection 时,length
属性很有用。
HTMLCollection
HTMLCollection 是一个类数组的 HTML 元素集合(列表)。
集合中的元素可以通过索引访问。索引从 0 开始。
语法
HTMLCollection.length
返回值
类型 | 描述 |
Number | HTMLCollection 的元素数量。 |
浏览器支持
HTMLCollection.length
在所有浏览器中都受支持
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 是 |