DOM HTMLCollection
HTMLCollection 是 HTML 元素的集合。
HTMLCollection 對象類似一個包含 HTML 元素的數組列表。
getElementsByTagName() 方法返回的就是一個 HTMLCollection 對象。
屬性和方法
下表列出了 HTMLCollection 對象中的屬性和方法:
屬性 / 方法 | 描述 |
---|---|
item() | 返回 HTMLCollection 中指定索引的元素。 |
length | 返回 HTMLCollection 中元素的數量。 |
namedItem() | 返回 HTMLCollection 中指定 ID 或 name 屬性的元素。 |
實例
返回所有 p 元素的集合,該集合是一個 HTMLCollection 對象:
實例
var x = document.getElementsByTagName("p");
計算文檔中 p 元素的數量:
實例
var x = document.getElementsByTagName("P");
document.write(x.length);
迴圈輸出 HTMLCollection 對象中的所有元素:
實例
var x = document.getElementsByTagName("P");
document.write(x.length);