【问题标题】:How to change font color of all elements of a class through javascript?如何通过javascript更改类的所有元素的字体颜色?
【发布时间】:2020-05-03 23:53:12
【问题描述】:

我有一个按钮可以更改我的网络应用程序的背景图像,并且我想在单击该按钮时更改字体颜色。

我尝试将元素设为自己的变量,但这也不起作用。

cafeButton.addEventListener('click', function(){
    bg.style.backgroundImage = "url('img/cafe.jpeg')"; //change text colors
    document.getElementsByClassName('topbutton').style.color = 'blue';
})

使用上述代码时,我收到以下错误:

未捕获的类型错误:无法设置未定义的属性“颜色” 在 HTMLButtonElement。

这里是整个项目的codepenhttps://codepen.io/Games247/pen/XWJqebG

如何更改类名下所有元素的文本颜色?

【问题讨论】:

标签: javascript web dom


【解决方案1】:

document.getElementsByClassName 返回一个 DOM 节点列表。因此,您需要遍历它并将样式单独应用于所有元素。

cafeButton.addEventListener('click', function() {
  bg.style.backgroundImage = "url('img/cafe.jpeg')"; //change text colors
  var els = document.getElementsByClassName('topbutton');
  for (var i = 0; i < els.length; i++) {
    els[i].style.color = 'blue';
  }
})

【讨论】:

    【解决方案2】:

    getElementsByClassName 给你DOMCollection,它只是数组。因此,您必须为数组中的每个元素设置样式。 例如。

    [...document.getElementsByClassName('topbutton')].forEach((ele)=>{ele.style.color = 'blue';});
    

    【讨论】:

      【解决方案3】:

      你做错了。 document.getElementsByClassName 为您提供特定类的节点列表。所以你必须遍历它。所以,在你的代码中使用这个:

      var nodeList = document.getElementsByClassName('topbutton')
      nodeList.forEach(node => {
        node.style.color = 'blue'
      })
      

      或者你也可以用document.querySelectorAll('.topbutton')代替document.getElementsByClassName('topbutton')

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-02
        • 1970-01-01
        • 2018-08-06
        • 2014-08-14
        • 1970-01-01
        • 1970-01-01
        • 2012-01-01
        • 2015-01-02
        相关资源
        最近更新 更多