Search code examples
javascriptcoding-style

How can I set multiple CSS styles in JavaScript?


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 

Solution

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

    You can also use template literals for an easier, more readable multiline CSS-like syntax:

    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.