HTML DOM Document getElementsByClassName()
示例
獲取所有 class="example" 的元素
const collection = document.getElementsByClassName("example");
自己動手試一試 »
獲取所有同時具有 "example" 和 "color" 類的元素
const collection = document.getElementsByClassName("example color");
自己動手試一試 »
更多示例見下文。
描述
getElementsByClassName()
方法返回具有指定類名(或多個類名)的元素集合。
getElementsByClassName()
方法返回一個 HTMLCollection。
HTMLCollection
HTMLCollection 是一個類陣列的 HTML 元素集合(列表)。
length 屬性 返回集合中元素的數量。
元素可以透過索引訪問(從 0 開始)。
HTMLCollection 是即時的。當文件更改時它會自動更新。
另請參閱
語法
document.getElementsByClassName(classname)
引數
引數 | 描述 |
類名 | 必需。 元素的類名。 搜尋由空格分隔的多個類名,例如 "test demo"。 |
返回值
型別 | 描述 |
物件。 | 一個 HTMLCollection 物件。 具有指定類名的元素集合。 元素按其在文件中出現的順序排序。 |
更多示例
更改所有具有 class="example" 的元素的背景顏色
const collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "red";
}
自己動手試一試 »
相關頁面
CSS 教程:CSS 語法
CSS 參考:CSS .class 選擇器
HTML DOM 參考:element.getElementsByClassName()
HTML DOM 參考:className 屬性
HTML DOM 參考:classList 屬性
HTML DOM 參考:Style 物件
瀏覽器支援
document.getElementsByClassName()
是 DOM Level 1 (1998) 的一個特性。
所有瀏覽器都完全支援。
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 9-11 |