Using cssText

I've just had reason to look up the use of cssText. I've not actually used it before but perhaps I should — it provides a simple and efficient way of changing CSS styles through JavaScript. Perhaps? I'll get to cross browser support in a minute.

What The Text Books Tell You To Do

Read a text book or tutorial on defining styles using JavaScript and the chances are you'll be told that if you, say, want to set the background and padding on an element the way to do it is something like this:

<script>
  var f = document.getElementById("idOfElelment");
  f.style.backgroundColor="#eee";
  f.style.padding="0.2em";
</script>

That works but, like a lot of things that work, it can work better.

First of all you have to remember to use camel case for the properties rather than the native CSS lower-case-with-hyphens style. Hence backgroundColor rather than background-color.

Then you have to remember to use = to assign the values rather than the colon used natively by CSS.

In other words, you're not writing CSS, you're writing something a bit like CSS only in JavaScript, which is a pain. But how else can you do it?

What You Can Do Instead

You can just write CSS inline style definitions in the same was as you would in the markup — you just add the definitions to the cssText property of the style object thus:

document.getElementById("idOfElelment").style.cssText
  = "background-color: #eee; padding:0.2em";

Not only is this easier to do — assuming you're comfortable writing CSS definitions in the first place — but it's also more efficient. You're passing what is in effect a single set of instructions to the browser that it can execute in one go rather than separate instructions that can, potentially, cause multiple re-paintings of the screen. That's especially good for mobile

Let's give it a try. Enter a CSS definition in the text box below and hit the button. It will pass what you type into the cssText property of the relevant element's style object.

The Quick Brown Fox Jumped Over The Lazy Dog.

Is It Supported Cross Browser?

No sooner had I posted this than I was asked whether it was safe to use this cross browser. I did a quick check in all my (Win XP) desktop browsers where it worked just fine: Opera 11.61, Chrome 17, FF 10, IE 8, Safari 5.1. Likewise on my mobile - Android 2.1/Webkit 3.1. I looked it up on Quirksmode too — it all looked good … until I tried it on iOS devices iP(od|ad|hone) and found that at least my little test here doesn't work. It doesn't work on my old Nokia N95 either. Also, Steven Pemberton tells me that on his desktop version of Opera you need to include the semi-colon after the property for it to work.

Humph…

More investigation required but on first impressions this is a realy nice idea what works on all modern devices except Apple's non-desktop products. Oh the delicious irony…