此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

HTMLCollection.length

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

HTMLCollection.length 属性返回 HTMLCollection 中的元素数量。

一个正整数,表示 HTMLCollection 中元素的数量。

示例

length 属性在 DOM 编程中通常很有用。它通常用于测试集合的长度,去看它是否真的存在。它也通常用于 for 循环中的迭代器,如下示例。

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

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

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

规范

Specification
DOM
# ref-for-dom-htmlcollection-length①

浏览器兼容性