文档:getElementsByClassName() 方法
getElementsByClassName 是 Document 接口的一个方法,它返回一个类数组对象,其中包含所有具有给定类名的子元素。
当在 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.querySelector 和 document.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① | 
浏览器兼容性
加载中…