Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 430
Nir Avatar asked Jun 11 '09 14:06

Nir


People also ask

Can JavaScript change the style of an element?

The HTML DOM allows JavaScript to change the style of HTML elements.

Can you style JavaScript with CSS?

Ignoring inline styles, the other approach that we can use to introduce elements to the goodness that is CSS styling involves JavaScript. We can use JavaScript to directly set a style on an element, and we can also use JavaScript to add or remove class values on elements which will alter which style rules get applied.


2 Answers

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

like image 67
ajm Avatar answered Sep 28 '22 16:09

ajm


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.

like image 30
Alex Rozanski Avatar answered Sep 28 '22 18:09

Alex Rozanski