JavaScript HTML DOM 集合

HTMLCollection 對象

getElementsByTagName() 方法返回 HTMLCollection 對象。

HTMLCollection 對象是類數組的 HTML 元素列表(集合)。

下面的代碼選取文檔中的所有 <p> 元素:

實例

var x = document.getElementsByTagName("p");

該集合中的元素可通過索引號進行訪問。

如需訪問第二個 <p> 元素,您可以這樣寫:

y = x[1];

親自試一試

注釋:索引從 0 開始。

HTML HTMLCollection 長度

length 屬性定義了 HTMLCollection 中元素的數量:

實例

var myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = myCollection.length; 

親自試一試

實例解釋:

  • 創建所有 <p> 元素的集合
  • 顯示集合的長度

length 屬性在您需要遍歷集合中元素時是有用的:

實例

改變所有 <p> 元素的背景色:

var myCollection = document.getElementsByTagName("p");
var i;
for (i = 0; i < myCollection.length; i++) {
    myCollection[i].style.backgroundColor = "red";
}

親自試一試

HTMLCollection 并非數組!

HTMLCollection 也許看起來像數組,但并非數組。

您能夠遍歷列表并通過數字引用元素(就像數組那樣)。

不過,您無法對 HTMLCollection 使用數組方法,比如 valueOf()pop()push()join()