2

What I'd like to do can be summarized like this: "if this condition is met, then do the following multiple actions." My code works fine for the first thing to be done, but I'm getting an "Uncaught SyntaxError: Unexpected token else" error when I add an additional action to be performed. I'll note the problem line below.

function turnonall(cl) {
    var elements = document.getElementsByClassName(cl);
      for (var i = 0; i < elements.length; i++){
        if (elements[i].style.display == 'none' || elements[i].style.display == '' || elements[i].style.display == 'block')
        elements[i].style.display = 'block';
        elements[i].style.className = 'buttonactive';  <--this line is throwing the error.
        else
        elements[i].style.display = 'none';
      }
  }
j08691
  • 204,283
  • 31
  • 260
  • 272
Chris
  • 51
  • 1
  • 8

2 Answers2

3

Your if/else statement's signature is incorrect. What you are attempting only works for if/else statements with one line in the if statement. Once you add more than one line to a bracketless if/else, brackets are required

Simply wrap your if and else block in brackets like so:

function turnonall(cl) {
  var elements = document.getElementsByClassName(cl);
  for (var i = 0; i < elements.length; i++) {
    if (elements[i].style.display == 'none' || elements[i].style.display == '' || elements[i].style.display == 'block') {
      elements[i].style.display = 'block';
      elements[i].style.className = 'buttonactive';
    } else {
      elements[i].style.display = 'none';
    }
  }
}

You're not 100% incorrect, however. This, for example, is valid JavaScript:

if (true)
  console.log('it is true')
else
  console.log('it is not true')

But this is not

if (true)
  console.log('it is true')
  console.log('and I like it')
else
  console.log('it is not true')
Seth
  • 10,198
  • 10
  • 45
  • 68
0
function turnonall(cl) {
    var elements = document.getElementsByClassName(cl);
      for (var i = 0; i < elements.length; i++){
        if (elements[i].style.display == 'none' || elements[i].style.display == '' || elements[i].style.display == 'block')
        {  // Bracket!
            elements[i].style.display = 'block';
            elements[i].style.className = 'buttonactive';  <--this line is throwing the error.
        }  // Bracket!
        else
            elements[i].style.display = 'none';
      }
  }
Amit Gold
  • 727
  • 7
  • 22
  • @Chris pointing out that once you accept another answer you unaccept the 1st answer that you accepted. (Just to make you familiar with the system, totally not to hint you to accept my answer instead). Also you can upvote answers which are good but not best. – Amit Gold Feb 20 '16 at 20:13
  • yes, sorry for the mix up. btw, I've upvoted your answer, but I guess it doesn't display until my reputation score improves. – Chris Feb 20 '16 at 21:06