2

Is it possible to change the CSS class of an HTML button using JavaScript?

I tried this but it didn't work:

document.getElementById("btnChoice1").setAttribute("class", "redButton");

HTML Button

<button class="basicButton" id="btnChoice1">

CSS

.basicButton {
    width:300px;
}

.redButton {
    width:300px;
    background-color:red;
}
user1822824
  • 2,478
  • 6
  • 41
  • 65

4 Answers4

3

Try document.getElementById("btnChoice1").className = 'redButton'.

sevenseacat
  • 24,699
  • 6
  • 63
  • 88
3

className is preferred but your setAttribute() code should work. If it's not working then you probably have the Javascript executing before the button exists on the page.

Check that the code is within an window.onload event or is after the button markup.

MrCode
  • 63,975
  • 10
  • 90
  • 112
2

you could try it with this code:

document.getElementById("btnChoice1").className = "redButton";

if you want to use jquery you have to write it like this:

(document.getElementById("btnChoice1")).setAttribute("class", "redButton");

Greets Knerd

Knerd
  • 1,892
  • 3
  • 28
  • 55
0

Your code works.

You probbably didn't put the javascript where it should be or you have some error in your code so javascript doesn't execute.

<button id="change" onClick="document.getElementById('btnChoice1').setAttribute('class', 'redButton');">change</button>

<button class="basicButton" id="btnChoice1">
    test
</button>

Proof that your code is working here http://jsfiddle.net/nDmKP/

Udan
  • 5,429
  • 2
  • 28
  • 34