Lenny Magico
Lenny Magico

Reputation: 1203

JavaScript onClick change css

This is probably really simple, I know you can change css properties with javascript by doing;

document.getElementById('bob').style.background='#000000';

But I recently found out that you can do this differently and style multiple things, so something like this;

document.getElementById('bob').css='background:#ffffff; color: #000000;';

the problem is I have forgotten what the code, So what I basically want to achieve is what goes in instead of the ".css"? Does anyone know the code I need out the top of their head?

Upvotes: 7

Views: 51227

Answers (4)

melhosseiny
melhosseiny

Reputation: 10144

document.getElementById('bob').style.cssText = 
    'background:#ffffff; color: #000000;';

Upvotes: 2

Erick Petrucelli
Erick Petrucelli

Reputation: 14872

I think what you is looking for is Change an element's class with JavaScript. Since this way you don't need to hardcode all the style changes on the JavaScript itself (which is bad).

So you'll have a CSS class like it:

.myClass {
    background: #ffffff;
    color: #000000;
}

And you'll set to your element like this:

document.getElementById("MyElement").className += " myClass";

Upvotes: 3

Kevin
Kevin

Reputation: 5694

Have a look at this fiddle: http://jsfiddle.net/YSJfz/

document.getElementById('myDiv').setAttribute('style', 'background: #f00; color: #fff;');

All I do is change the style attribute of the element, is that what you meant to accomplish?

Upvotes: 8

jAndy
jAndy

Reputation: 235962

I guess you're looking for the .cssText property from style

document.getElementById('bob').style.cssText = 'background:#ffffff; color: #000000;';

Example: http://jsfiddle.net/Sx5yH/

Upvotes: 20

Related Questions