ZetCode

JavaScript getElementsByClassName

最后修改于 2025 年 4 月 2 日

在本文中,我们将探讨 JavaScript 中的 document.getElementsByClassName 方法。此方法对于 DOM 操作至关重要,它允许开发人员通过其 class 属性访问元素。

基本定义

document.getElementsByClassName 方法返回一个包含指定类名的元素的实时 HTMLCollection。与 ID 不同,多个元素可以共享同一个类名。

此方法接受一个或多个以空格分隔的类名。它会搜索整个文档,但也可以在特定元素上调用,仅搜索其后代元素。

基本的 getElementsByClassName

此示例演示了如何访问具有特定类名的元素。

index.html
<!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');
    console.log(items.length); // Outputs: 3
    console.log(items[0].textContent); // Outputs: First item
</script>

</body>
</html>

在这个基本示例中,我们有三个 class 为 "item" 的 div 元素。JavaScript 代码使用 getElementsByClassName 检索所有具有此类名的元素。

该方法返回一个 HTMLCollection,它类似数组但并非真正的数组。我们可以通过索引访问元素并检查集合的长度。

修改多个元素

此示例展示了如何修改所有具有特定类名的元素。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Modifying Multiple Elements</title>
</head>
<body>

<p class="highlight">First paragraph</p>
<p class="highlight">Second paragraph</p>
<p class="highlight">Third paragraph</p>
<button onclick="highlightAll()">Highlight All</button>

<script>
    function highlightAll() {
        const elements = document.getElementsByClassName('highlight');
        for (let i = 0; i < elements.length; i++) {
            elements[i].style.backgroundColor = 'yellow';
        }
    }
</script>

</body>
</html>

在这里,我们有三个 class 为 "highlight" 的段落元素和一个按钮。当点击按钮时,会触发一个函数,将所有元素的背景颜色更改为黄色。

这演示了如何遍历 HTMLCollection 来一次性修改多个元素。该集合是实时的,这意味着如果元素被添加到 DOM 中或从 DOM 中移除,它会自动更新。

多个类名

此示例演示了在 getElementsByClassName 中使用多个类名。

index.html
<!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>
    // Get elements with both 'box' and 'red' classes
    const redBoxes = document.getElementsByClassName('box red');
    console.log(redBoxes.length); // Outputs: 2
    
    // Get elements with all three classes
    const largeRedBoxes = document.getElementsByClassName('box red large');
    console.log(largeRedBoxes.length); // Outputs: 1
</script>

</body>
</html>

在此示例中,我们有具有多个类名的 div 元素。该方法可以接受以空格分隔的多个类名,以查找包含所有指定类的元素。

方法调用中类名的顺序无关紧要,但元素必须包含所有指定的类名才能包含在结果中。

与查询选择器结合使用

此示例展示了如何将 getElementsByClassName 与查询选择器结合使用。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Combining Methods</title>
</head>
<body>

<div id="container">
    <p class="message">First message</p>
    <p class="message">Second message</p>
</div>
<p class="message">Third message</p>

<script>
    // Get container element first
    const container = document.getElementById('container');
    
    // Then get messages only within container
    const containerMessages = container.getElementsByClassName('message');
    console.log(containerMessages.length); // Outputs: 2
    
    // Compare with document-wide search
    const allMessages = document.getElementsByClassName('message');
    console.log(allMessages.length); // Outputs: 3
</script>

</body>
</html>

在这里,我们演示了如何通过首先选择父元素,然后在父元素上调用 getElementsByClassName 来限定类名搜索范围。

当您想将搜索范围限制在文档的特定部分时,这种技术很有用,它可以提高性能并避免意外匹配。

转换为数组

此示例显示如何将 HTMLCollection 转换为标准数组。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Converting to Array</title>
</head>
<body>

<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>

<script>
    // Get HTMLCollection
    const cardsCollection = document.getElementsByClassName('card');
    
    // Convert to array using Array.from()
    const cardsArray = Array.from(cardsCollection);
    
    // Now we can use array methods
    cardsArray.forEach(card => {
        card.style.border = '2px solid black';
    });
    
    console.log(cardsArray.map(card => card.textContent));
</script>

</body>
</html>

在此示例中,我们使用 Array.from() 将 getElementsByClassName 返回的 HTMLCollection 转换为标准数组。这使我们可以使用 forEach 和 map 等数组方法。

虽然 HTMLCollection 具有一些类似数组的属性(length,索引访问),但转换为真正的数组可以为操作元素提供更大的灵活性和功能。

来源

MDN getElementsByClassName 文档

在本文中,我们展示了如何在 JavaScript 中使用 document.getElementsByClassName。此方法对于在 Web 开发中按类名选择多个元素至关重要。

作者

我叫 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。至今,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 JS DOM 教程