setting a whole style string to an element from javascript (not individual style parameters)

Nir picture Nir · Jun 11, 2009 · Viewed 35.3k times · Source

I need to set an arbitrary style to a span via javascript.

I know I can do things like: span.style.height="250px"; But I need to be able to insert a random full style definition from a template

for example

float:left; 
text-decoration:underline; 
cursor:pointer; 
color:blue;

Is there a way to do that in Javascript? Something like:

element.style="all style definition here";

Answer

ajm picture ajm · Jun 11, 2009

How about the .style.cssText property? Here's Microsoft's explanation.

Throw it the styles you'd like to apply like so:

document.getElementById('myEl').style.cssText = 'float:left;margin-top:75px;';

As for browser support, although it was IE-proprietary I believe it's well-supported (works in the IEs, FF3, and Safari 3.2 WIN at least).