文件:getElementsByClassName() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

getElementsByClassNameDocument 介面的一個方法,它返回一個類陣列物件,其中包含所有具有給定類名的子元素。

當在 document 物件上呼叫時,會搜尋整個文件,包括根節點。您也可以在任何元素上呼叫 getElementsByClassName();它只會返回作為指定根元素後代的、具有給定類名的元素。

警告:這是一個即時的 HTMLCollection。DOM 中的更改會即時反映在陣列中。如果陣列中透過此方法選中的元素不再符合選擇器,它將被自動移除。在進行迭代時請注意這一點。

語法

js
getElementsByClassName(names)

引數

names

一個字串,表示要匹配的類名;多個類名用空格分隔。

返回值

一個包含找到的元素的即時 HTMLCollection

示例

獲取所有類名為 'test' 的元素

js
document.getElementsByClassName("test");

獲取同時具有 'red' 和 'test' 類的所有元素

js
document.getElementsByClassName("red test");

獲取 ID 為 'main' 的元素內部,類名為 'test' 的所有元素

js
document.getElementById("main").getElementsByClassName("test");

獲取第一個類名為 'test' 的元素,如果沒有找到匹配的元素則返回 undefined

js
document.getElementsByClassName("test")[0];

我們也可以透過將 HTMLCollection 作為方法的 this 值來在任何 HTMLCollection 上使用 Array.prototype 的方法。在這裡,我們將查詢所有類名為 'test' 的 div 元素。

js
const testElements = document.getElementsByClassName("test");
const testDivs = Array.prototype.filter.call(
  testElements,
  (testElement) => testElement.nodeName === "DIV",
);

獲取第一個類名為 'test' 的元素

這是最常用的操作方法。

html
<div id="parent-id">
  <p>hello world 1</p>
  <p class="test">hello world 2</p>
  <p>hello world 3</p>
  <p>hello world 4</p>
</div>
js
const parentDOM = document.getElementById("parent-id");

const test = parentDOM.getElementsByClassName("test"); // a list of matching elements, *not* the element itself
console.log(test); // HTMLCollection[1]

const testTarget = parentDOM.getElementsByClassName("test")[0]; // the first element, as we wanted
console.log(testTarget); // <p class="test">hello world 2</p>

多類名示例

document.getElementsByClassName 的工作方式與 document.querySelectordocument.querySelectorAll 非常相似。只選擇包含所有指定類名的元素。

HTML

html
<span class="orange fruit">Orange Fruit</span>
<span class="orange juice">Orange Juice</span>
<span class="apple juice">Apple Juice</span>
<span class="foo bar">Something Random</span>
<textarea id="resultArea"></textarea>

JavaScript

js
// getElementsByClassName only selects elements that have both given classes
const allOrangeJuiceByClass = document.getElementsByClassName("orange juice");
let result = "document.getElementsByClassName('orange juice')";
for (const el of allOrangeJuiceByClass) {
  result += `\n  ${el.textContent}`;
}

// querySelector only selects full complete matches
const allOrangeJuiceQuery = document.querySelectorAll(".orange.juice");
result += "\n\ndocument.querySelectorAll('.orange.juice')";
for (const el of allOrangeJuiceQuery) {
  result += `\n  ${el.textContent}`;
}

document.getElementById("resultArea").value = result;

結果

規範

規範
DOM
# ref-for-dom-document-getelementsbyclassname①

瀏覽器相容性