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①

瀏覽器相容性