如何通过javascript更改类的所有元素的字体颜色?

问题描述 投票:0回答:3

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

我尝试使该元素成为其自己的变量,但这也不起作用。

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

使用上述代码时,出现以下错误:

Uncaught TypeError:无法设置未定义的属性'color'在HTMLButtonElement。

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

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

javascript web dom
3个回答
0
投票

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';
  }
})

0
投票

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

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

0
投票

您的操作方式有误。 document.getElementsByClassName为您提供特定类别的节点列表。因此,您必须遍历它。因此,在您的代码中使用以下代码:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.