1

I have a button that changes the background image of my web app, and I want to change the color of the font when the button is clicked.

I tried making the element its own variable but that didn't work either.

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

When using the above code I get the following error:

Uncaught TypeError: Cannot set property 'color' of undefined at HTMLButtonElement.

Here is a codepen of the whole project https://codepen.io/Games247/pen/XWJqebG

How do I change the text color of all elements under a class name?

games247
  • 65
  • 1
  • 10

3 Answers3

2

document.getElementsByClassName returns a list of DOM Node. So you need to loop through it and apply styles to all elements individually.

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';
  }
})
Archie
  • 901
  • 4
  • 11
1

getElementsByClassName gives you DOMCollection, which is nothing but array. Hence, you have to style each element inside array. eg.

[...document.getElementsByClassName('topbutton')].forEach((ele)=>{ele.style.color = 'blue';});
Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30
0

You are doing it in the wrong way. document.getElementsByClassName gives you a node list of a specific class. So you have to loop through it. So, in your code use this:

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

Or you can also use document.querySelectorAll('.topbutton') instead of document.getElementsByClassName('topbutton')

Nipun Jain
  • 999
  • 6
  • 13