JavaScript getElementsByClassName
最后修改于 2025 年 4 月 2 日
在本文中,我们将探讨 JavaScript 中的 getElementsByClassName 方法。此方法对于 DOM 操作至关重要,它允许开发人员按其 class 属性访问元素。
基本定义
getElementsByClassName 方法返回一个包含具有指定类名(或多个类名)的元素的实时 HTMLCollection。它可以应用于 document 对象或任何 DOM 元素。
与 ID 不同,类名不需要是唯一的。多个元素可以共享相同的类名。该方法按文档顺序返回所有匹配的元素。
返回的集合是实时的,这意味着当 DOM 发生更改时,它会自动更新。您可以指定多个类名,用空格分隔。
基本 getElementsByClassName
本示例演示了如何访问具有特定类名的元素。
<!DOCTYPE html>
<html>
<head>
<title>Basic getElementsByClassName</title>
</head>
<body>
<div class="item">First item</div>
<div class="item">Second item</div>
<div class="item">Third item</div>
<script>
const items = document.getElementsByClassName('item');
for (let i = 0; i < items.length; i++) {
console.log(items[i].textContent);
}
</script>
</body>
</html>
在这个基本示例中,我们有三个 class 为 "item" 的 div 元素。JavaScript 代码使用 getElementsByClassName 检索具有该类的所有元素。
该方法返回一个 HTMLCollection,我们通过 for 循环进行迭代。对于每个元素,我们将它的文本内容记录到控制台。
多个类名
本示例展示了如何选择具有多个类名的元素。
<!DOCTYPE html>
<html>
<head>
<title>Multiple Class Names</title>
</head>
<body>
<div class="box red">Red Box</div>
<div class="box blue">Blue Box</div>
<div class="box red large">Large Red Box</div>
<script>
const redBoxes = document.getElementsByClassName('red box');
for (let box of redBoxes) {
box.style.border = '2px solid black';
}
</script>
</body>
</html>
这里我们有各种类组合的 div 元素。我们使用 getElementsByClassName,并用空格分隔两个类名。
这只会选择同时具有 "red" 和 "box" 类的元素。然后,我们使用 for...of 循环为每个匹配的元素添加黑色边框。
限定在父元素范围
本示例演示了如何将搜索范围限定在特定的父元素。
<!DOCTYPE html>
<html>
<head>
<title>Scoped Search</title>
</head>
<body>
<div id="container">
<div class="item">Container Item 1</div>
<div class="item">Container Item 2</div>
</div>
<div class="item">Outside Item</div>
<script>
const container = document.getElementById('container');
const containerItems = container.getElementsByClassName('item');
console.log('Items in container:', containerItems.length);
</script>
</body>
</html>
在此示例中,我们首先使用 getElementById 获取对容器元素的引用。然后,我们在该容器元素上调用 getElementsByClassName。
这将搜索范围仅限于我们容器的后代中 class 为 "item" 的元素。外部的 item 不包含在结果中。
修改多个元素
本示例展示了如何修改由 getElementsByClassName 返回的多个元素。
<!DOCTYPE html>
<html>
<head>
<title>Modifying Multiple Elements</title>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<p class="text">First paragraph</p>
<p class="text">Second paragraph</p>
<p class="text">Third paragraph</p>
<button onclick="highlightText()">Highlight Text</button>
<script>
function highlightText() {
const paragraphs = document.getElementsByClassName('text');
for (let p of paragraphs) {
p.classList.add('highlight');
}
}
</script>
</body>
</html>
这里我们有多个 class 为 "text" 的段落。当按钮被点击时,highlightText 函数会获取所有这些段落,并为每个段落添加 "highlight" 类。
这演示了如何一次性对多个元素应用更改。我们使用 classList.add 添加新类,而不是直接操作样式属性。
实时集合行为
本示例演示了 getElementsByClassName 返回的 HTMLCollection 的实时特性。
<!DOCTYPE html>
<html>
<head>
<title>Live Collection</title>
</head>
<body>
<div class="dynamic">Initial Item</div>
<button onclick="addItem()">Add Item</button>
<button onclick="showCount()">Show Count</button>
<script>
const dynamicItems = document.getElementsByClassName('dynamic');
function addItem() {
const newItem = document.createElement('div');
newItem.className = 'dynamic';
newItem.textContent = 'New Item ' + (dynamicItems.length + 1);
document.body.appendChild(newItem);
}
function showCount() {
alert('Total items: ' + dynamicItems.length);
}
</script>
</body>
</html>
在此示例中,我们将 class 为 "dynamic" 的元素集合存储在一个变量中。当添加新元素时,集合会自动更新。
点击 "Add Item" 会创建并追加一个具有相同类的新 div。点击 "Show Count" 会显示集合的当前长度,该长度会随着每个添加的元素而增加。
来源
在本文中,我们展示了如何在 JavaScript 中使用 getElementsByClassName。此方法对于在 Web 开发中按类名选择多个元素至关重要。
作者
列出 所有 JS DOM 教程。