You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中使用.getElementsByClassName修改元素背景色

问题原因

document.getElementsByClassName() 方法返回的是包含所有匹配类名元素的类数组集合(HTMLCollection),不是单个DOM元素,你直接给整个集合设置.style.background是无效的,必须遍历集合中的每一个元素,分别设置样式。
document.getElementById() 只返回唯一的单个DOM元素,所以可以直接设置样式,这就是两种方法表现不同的根本原因。

修正后的JS代码

function changeBgColor(color){
    document.getElementById("background1").style.background = color;
}

function changeBackground(color){
    // 获取所有匹配类名的元素集合
    const elements = document.getElementsByClassName("pls-work");
    // 遍历每个元素单独设置样式
    for(let i = 0; i < elements.length; i++){
        elements[i].style.background = color;
    }
}

可选简化实现方案

你也可以用document.querySelectorAll()方法配合forEach遍历,写法更简洁:

function changeBackground(color){
    document.querySelectorAll(".pls-work").forEach(el => {
        el.style.background = color;
    })
}

注意querySelectorAll的参数需要加上类选择器的.前缀。

内容的提问来源于stack exchange,提问作者ixcode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:54:02