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
Your best bet may be to create a function that sets styles on your own:
Note that you will still have to use the javascript-compatible property names (hence
backgroundColor
)This is old thread, so I figured for anyone looking for a modern answer, I would suggest using Object.keys();
I just stumbled in here and I don't see why there is so much code required to achieve this.
Add your CSS code as a string.
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: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.
Using Object.assign:
This also gives you ability to merge styles, instead of rewriting the CSS style.
You can also make a shortcut function:
A JavaScript library allows you to do these things very easily
jQuery
Object and a for-in-loop
Or, a much more elegant method is a basic object & for-loop