JavaScript HTML DOM 集合
HTMLCollection 物件
getElementsByTagName()
方法返回一個 HTMLCollection
物件。
HTMLCollection
物件是一個類似陣列的 HTML 元素列表(集合)。
以下程式碼選擇文件中的所有 <p>
元素
示例
const myCollection = document.getElementsByTagName("p");
集合中的元素可以透過索引號訪問。
要訪問第二個 <p> 元素,您可以這樣寫
myCollection[1]
自己動手試一試 »
注意:索引從 0 開始。
HTML HTMLCollection 長度
length
屬性定義了 HTMLCollection
中元素的數量
length
屬性在您想要遍歷集合中的元素時非常有用
示例
更改所有 <p> 元素的文字顏色
const myCollection = document.getElementsByTagName("p");
for (let i = 0; i < myCollection.length; i++) {
myCollection[i].style.color = "red";
}
自己動手試一試 »
HTMLCollection 不是陣列!
HTMLCollection 可能看起來像一個數組,但它不是。
您可以遍歷列表並用數字引用元素(就像陣列一樣)。
但是,您不能在 HTMLCollection 上使用 valueOf()、pop()、push() 或 join() 等陣列方法。