tags:

views:

1010

answers:

3

I want to do this:

e.className = t;

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

+2  A: 

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. :-)

Chris Jester-Young
+17  A: 

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';
jonah
+2  A: 

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.
e-satis