user1822824
user1822824

Reputation: 2488

Change CSS Class of Button Using JavaScript

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

Answers (4)

Udan
Udan

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

MrCode
MrCode

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

Knerd
Knerd

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

sevenseacat
sevenseacat

Reputation: 25029

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

Upvotes: 3

Related Questions