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

41,481

Solution 1

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).

Solution 2

If you want it to be lightweight, create a function such as:

function setStyles(element, styles)
{
    for(var s in styles) {
        element.style[s] = styles[s];
    }
}

Then you would pass the styles in as an object literal:

setStyles(element, {float: "left",
                    textDecoration: "underline",
                    cursor: "pointer",
                    color: "blue"});

Note that the style references passed in have to follow the naming from a JavaScript standpoint, since the function simply changes the styles by accessing the element's style object through JavaScript.

If you must take your style input from a string then you could quite easily parse it and create the object literal.

Solution 3

There is element.setAttribute('style', '...');, but it fails in IE.

There is a solution, but I haven't tried.

Share:
41,481
Nir
Author by

Nir

Updated on September 27, 2020

Comments

  • Nir
    Nir almost 4 years

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

  • panzi
    panzi almost 12 years
    It should be document.getElementById('myEl').style.cssText = 'float:left;margin-top:75px;';, because cssText is a string, not a function.
  • ajm
    ajm almost 12 years
    Good catch. It should have been a string for the last 3 years! :-)
  • Campbeln
    Campbeln about 9 years
    FYI: Here's the Quirksmode info on .cssText
  • www139
    www139 almost 9 years
    Amazing, this is a life saver! Thanks for the answer :)