Joe
Joe

Reputation: 409

Can an element's CSS class be set via JavaScript?

I want to do this:

e.className = t;

Where t is the name of a style I have defined in a stylesheet.

Upvotes: 3

Views: 2845

Answers (5)

Mouzam Ali
Mouzam Ali

Reputation: 47

document.getElementById('id').className = 't'

Upvotes: 0

user14325562
user14325562

Reputation:

Here is the example that add and remove the class using jQuery.

// js
  $("p:first").addClass("t");
  $("p:first").removeClass("t");

// css
  .t {
    backgound: red
  }

Upvotes: 1

Bite code
Bite code

Reputation: 596663

Not only that works, but it's even a best practice.

You definitively want to separate the data format (xHTML) from the design (CSS) and the behaviour (javascript).

So it's far better to just add and remove classes in JS according to event while the esthetic concerns are delegated to css styles.

E.G : Coloring an error message in red.

CSS

.error
{
    color: red;
}

JS

var error=document.getElementById('error');
error.className='error';

N.B :

  • This snippet is just an example. In real life you would use js just for that.
  • document.getElementById is not always interoperable. Better to use a JS framework to handle that. I personally use JQuery.

Upvotes: 2

jonah
jonah

Reputation: 255

If e is a reference to a DOM element and you have a class like this: .t {color:green;} then you want reference the class name as a string:

e.className = 't';

Upvotes: 19

C. K. Young
C. K. Young

Reputation: 223003

Yes, that works (with the class name as a string, as jonah mentioned). Also, you can set style attributes directly on an object, using the DOM Level 2 Style interface. e.g.,

button.style.fontFamily = "Verdana, Arial, sans-serif";

where button is (presumably) a button object. :-)

Upvotes: 2

Related Questions