How can I set multiple CSS styles in JavaScript?

Mircea picture Mircea · Oct 19, 2010 · Viewed 273.7k times · Source

I have the following JavaScript variables:

var fontsize = "12px"
var left= "200px"
var top= "100px"

I know that I can set them to my element iteratively like this:

document.getElementById("myElement").style.top=top
document.getElementById("myElement").style.left=left

Is it possible to set them all together at once, something like this?

document.getElementById("myElement").style = allMyStyle 

Answer

Felix Kling picture Felix Kling · Oct 19, 2010

If you have the CSS values as string and there is no other CSS already set for the element (or you don't care about overwriting), make use of the cssText property:

document.getElementById("myElement").style.cssText = "display: block; position: absolute";

This is good in a sense as it avoids repainting the element every time you change a property (you change them all "at once" somehow).

On the other side, you would have to build the string first.