MCGuy MCGuy - 4 days ago 5
Javascript Question

Using an "If statement" to get the value of the coloured text in Javascript

I'm trying to make a thing where when you click a button, the text will turn green, and if you click it again, the text will turn blue. My strategy in doing this was to test if the text was green or if it was blue, but I didn't know how:

var topcon = document.getElementsByClassName("topchoice");

function show() {
if(topcon.style.color = "blue") {
for (count=0; count < topcon.length; count++) {
topcon[count].style.color = "green";
}
}
else if(topcon.style.color = "green") {
for (count=0; count < topcon.length; count++) {
topcon[count].style.color = "blue";
}
}
}


However, this doesn't work. It will just stay the same colour when I call the
show()
function. Does anyone know why this doesn't work?

And if you're wondering why I used a loop, that is because you can't
getElementsByClassName
without an array, because elements work with arrays.

Answer

There are 2 issues in the code

  • Need to use comparison operator == or === for comparison
  • topcon is a node list, so it does not have the style property. This will cause your code to throw an error like Uncaught TypeError: Cannot set property 'color' of undefined

var topcon = document.getElementsByClassName("topchoice");

function show() {
  var el;
  for (count = 0; count < topcon.length; count++) {
    el = topcon[count];
    if (el.style.color == "blue") {
      el.style.color = "green";
    } else if (el.style.color == "green") {
      el.style.color = "blue";
    }
  }
}
<div class="topchoice" style="color: green">1</div>
<div class="topchoice" style="color: green">1</div>
<div class="topchoice" style="color: green">1</div>
<div class="topchoice" style="color: green">1</div>

<button onclick="show()">Show</button>

Comments