Reputation: 2488
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;
}
Upvotes: 2
Views: 21954
Reputation: 5599
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/
Upvotes: 0
Reputation: 64526
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.
Upvotes: 3
Reputation: 2002
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
Upvotes: 2
Reputation: 25029
Try document.getElementById("btnChoice1").className = 'redButton'
.
Upvotes: 3