DOM HTMLCollection 參考手冊

HTMLCollection 對象

HTMLCollection 對象是 HTML 元素的類似數組的列表。

諸如 getElementsByTagName() 之類的方法會返回 HTMLCollection。

屬性和方法

可以在 HTMLCollection 對象上使用以下屬性和方法:

屬性 / 方法 描述
item() 返回 HTMLCollection 中指定索引處的元素。
length 返回 HTMLCollection 中的元素數。
namedItem() 返回 HTMLCollection 中有指定 ID 或名稱的元素。

實例

實例

獲取 HTMLCollection:

var x = document.getElementsByTagName("P");
// 返回文檔中所有 P 元素的集合

親自試一試

實例

輸出文檔中 <p> 元素的數量:

var x = document.getElementsByTagName("P");
document.write(x.length);

親自試一試

實例

循環遍歷 HTMLCollection 中的每個元素:

x = document.getElementsByTagName("*");
l = x.length;
for (i = 0; i < l; i++) {
  document.write(x[i].tagName + "<br>");
}

親自試一試