1

I have a button whose background color i wanna change on a certain condition. When I use the ID it works, but not when i use the classname. Any ideas?

Button:

<a href="" class="btn btn-default" id="reset" onclick="reset();" style="width:150px; background-color:black; color:white;">Zurücksetzen</a>

Code:

... if(com == true && (IDs.length >= correctOrder.length))
    {
        document.getElementsByClassName('btn btn-default').style.backgroundColor = "green";
        document.getElementById('messagewindow')
        .innerHTML = 'Done!';
    }else
    {
        document.getElementsByClassName('btn btn-default').style.backgroundColor = "red";
        document.getElementById('messagewindow')
        .innerHTML = 'Try again!';
    }
obi89
  • 33
  • 4
  • a quick guess; If you use the ID, you get the actual object, where you can apply a CSS Rule, but if you use the class, it returns a collection, since a class can appear multiple times (an ID should only appear once) – Matthias Seifert May 16 '18 at 12:56

1 Answers1

4

document.getElementsByClassName() return a node collection so if you have just one element targeted by that class name you need to access the first element

document.getElementsByClassName('btn-default')[0]

in this case you could also use querySelector()

document.querySelector('.btn-default')
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177