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?

1
  • nope :( grrrr, should have written it down Commented May 30, 2011 at 12:45

4 Answers 4

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/

Sign up to request clarification or add additional context in comments.

1 Comment

@Šime Vidas: as far as I can tell, yes! But I don't know about IE6 and below or FF < 3 for instance.
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?

Comments

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";

1 Comment

Yeh I know you can do it this way, but I think I need the .cssText for what I'm trying to do, but thanks anyway :D
2
document.getElementById('bob').style.cssText = 
    'background:#ffffff; color: #000000;';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.