2

I have a code which was supposed to toggle color between transparent and white on button click. This is the codepen link.

The div I want the color changed has the class points

<div class="points">100 points</div>

But running this javascript code returns an error

 document.getElementsByClassName('points').style.color = color;

Uncaught TypeError: Cannot read property 'color' of undefined

greenn
  • 309
  • 1
  • 6
  • 18

2 Answers2

-1

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.

Use the following code to achieve what you want -

var elements = document.getElementsByClassName("points");
var i;
for (i = 0; i < elements.length; i++) {
    elements[i].style.color = color;
}
Rishikesh Dhokare
  • 3,559
  • 23
  • 34
-1

The document.getElementsByClassName() Returns an array of controls, and in your code, there is not any specific index position to set the style for that particular element or control.

The modified working code as:

document.getElementsByClassName('points')[0].style.color = 'red';

console.log(document.getElementsByClassName('points'));
<div class="points">100 points</div>


 
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84