HTMLCollection:length 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

HTMLCollection.length 属性返回 HTMLCollection 中项目的数量。

一个整数值,表示 HTMLCollection 中项目的数量。

示例

length 属性在 DOM 编程中非常有用。它常用于测试列表的长度,以查看它是否存在。它也常被用作 for 循环的迭代器,如下例所示。

js
// All the elements with the class ".test" in the document
const items = document.getElementsByClassName("test");

// For each test item in the list,
// append the entire element as a string of HTML
let gross = "";
for (let i = 0; i < items.length; i++) {
  gross += items[i].innerHTML;
}

// gross is now all the HTML for the test elements

规范

规范
DOM
# ref-for-dom-htmlcollection-length①

浏览器兼容性