Element:getElementsByClassName() 方法

Baseline 已广泛支持

此功能已非常成熟,可在多种设备和浏览器版本上使用。自 2017 年 10 月以来,它已在各大浏览器中可用。

Element 方法 getElementsByClassName() 返回一个实时 HTMLCollection,其中包含具有指定类名或类名的所有后代元素。

Document 接口上的方法 getElementsByClassName() 的工作方式基本相同,只是它作用于整个文档,从文档根目录开始。

语法

js
getElementsByClassName(names)

参数

names

一个包含一个或多个要匹配的类名的字符串,用空格分隔。

返回值

一个 HTMLCollection,提供一个实时更新的列表,其中包含 names 中所有类的成员的每个元素。

用法说明

一如既往,返回的集合是实时的,这意味着它始终反映函数调用时所作用的元素所关联的 DOM 树的当前状态。当匹配 names 的新元素被添加到子树中时,它们会立即出现在集合中。同样,如果一个现有元素不再匹配 names,并且其类集被调整为匹配,它也会立即出现在集合中。

反之亦然;当元素不再匹配类名集时,它们会立即从集合中删除。

注意:混杂模式下,类名比较是不区分大小写的。否则,它们是区分大小写的。

示例

匹配单个类

要查找包含单个指定类的元素,我们在调用 getElementsByClassName() 时仅提供该类名。

js
element.getElementsByClassName("test");

此示例查找所有具有 test 类的元素,这些元素也是 idmain 的元素的后代。

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

匹配多个类

查找类列表中同时包含 redtest 类的元素。

js
element.getElementsByClassName("red test");

检查结果

您可以使用返回的 HTMLCollection 上的 item() 方法或标准的数组语法来检查集合中的单个元素。但是,下面的代码可能不会按预期工作,因为只要删除了任何 "color-box" 类,"matches" 就会改变。

js
const matches = element.getElementsByClassName("color-box");

for (let i = 0; i < matches.length; i++) {
  matches[i].classList.remove("color-box");
  matches.item(i).classList.add("hue-frame");
}

改为使用其他方法,例如

js
const matches = element.getElementsByClassName("color-box");

while (matches.length > 0) {
  matches.item(0).classList.add("hue-frame");
  matches[0].classList.remove("color-box");
}

此代码查找具有 "color-box" 类的后代元素,通过调用 item(0) 添加 "hue-frame" 类,然后删除 "color-box"(使用数组表示法)。另一个元素(如果还有剩余)将成为 item(0)

使用数组方法过滤结果

我们还可以通过将 HTMLCollection 作为方法的 this 值来在任何 HTMLCollection 上使用 Array 方法。这里我们将查找所有具有 test 类的 <div> 元素。

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

规范

规范
DOM
# ref-for-dom-element-getelementsbyclassname

浏览器兼容性