首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在.getElementsByClassName中使用JavaScript改变背景色?

如何在.getElementsByClassName中使用JavaScript改变背景色?
EN

Stack Overflow用户
提问于 2021-10-21 05:00:52
回答 7查看 356关注 0票数 0

不管我怎么尝试,我都不能让它起作用。如果我用.getElementById,它就能用.但是我需要针对多个divs,所以我需要使用.getElementsByClassName

到目前为止,我的情况如下:

代码语言:javascript
运行
复制
function changeBgColor(color){
        document.getElementById("background1").style.background = color;
    }
 
    function changeBackground(color){
        document.getElementsByClassName("pls-work").style.background = color;
    }
代码语言:javascript
运行
复制
  #background1{
        background: #c0c0c0;
        padding: 50px;
    color: #fafafa;
    }

    .background2{
        background: #ff7f50;
        padding: 20px;
    }
    
    .background3{
        background: #555;
        padding: 20px;
    }
代码语言:javascript
运行
复制
<h4>First example</h4>

    <div id="background1"><p>My background color will change.</p></div>

    <button onclick="changeBgColor('#222');">This function will work, no problem</button>
    
    <br><br>
    
<h4>Second example</h4>
    
    <div class="background3 pls-work"><p>My background color and my sibling's won't.</p></div>
    
    <div class="background2 pls-work"><p>I am the sibling</p></div>

    <button onclick="changeBackground('#222');">This will not work</button>

我到处搜索,但我找不到他们使用class而不是id的地方。

如果你能给我指点我做错了什么,我会很感激。

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2021-10-21 05:11:11

请试试这个,

首先,在变量中获取该元素,并对其进行循环。

代码语言:javascript
运行
复制
function changeBackground(color){
    var elements = document.getElementsByClassName("pls-work")
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.background=color;
        }
}
票数 1
EN

Stack Overflow用户

发布于 2021-10-21 05:06:30

getElementsByClassName返回需要迭代的元素的“类似数组的对象”,而不是返回单个元素的getElementById

看看这个:

代码语言:javascript
运行
复制
const changeBgColor = () => {
  const elements = document.getElementsByClassName('color-me');
  const color = document.querySelector('input').value;
  for (let i = 0; i < elements.length; i++) {
    elements[i].style.backgroundColor = color;
  }
};
代码语言:javascript
运行
复制
<p class='color-me'>Color me!</p>
<p>Can't change me..</p>
<p class='color-me'>Me too!</p>
<input type=color />
<button onclick=changeBgColor()>Click Me</button>

票数 1
EN

Stack Overflow用户

发布于 2021-10-21 05:08:41

document.getElementsByClassName("pls-work")的调用返回元素的HTMLCollection,而不是单个元素。您需要对集合进行迭代,并对每个元素设置样式属性。

请参阅JS:使用getElementsByClassName迭代Array.forEach的结果

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69656107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档