7

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?

Lenny Magico
  • 1,183
  • 5
  • 16
  • 28

4 Answers4

20

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/

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • @Šime Vidas: as far as I can tell, yes! But I don't know about IE6 and below or FF < 3 for instance. – jAndy May 30 '11 at 12:55
8

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?

kapa
  • 77,694
  • 21
  • 158
  • 175
Kevin
  • 5,626
  • 3
  • 28
  • 41
3

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";
Community
  • 1
  • 1
Erick Petrucelli
  • 14,386
  • 8
  • 64
  • 84
2
document.getElementById('bob').style.cssText = 
    'background:#ffffff; color: #000000;';
melhosseiny
  • 9,992
  • 6
  • 31
  • 48