How can I set multiple CSS styles in JavaScript?

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.


Using Object.assign:

Object.assign(yourelement.style,{fontsize:"12px",left:"200px",top:"100px"});

This also gives you ability to merge styles, instead of rewriting the CSS style.

You can also make a shortcut function:

const setStylesOnElement = function(styles, element){
    Object.assign(element.style, styles);
}

Make a function to take care of it, and pass it parameters with the styles you want changed..

function setStyle( objId, propertyObject )
{
 var elem = document.getElementById(objId);
 for (var property in propertyObject)
    elem.style[property] = propertyObject[property];
}

and call it like this

setStyle('myElement', {'fontsize':'12px', 'left':'200px'});

for the values of the properties inside the propertyObject you can use variables..


@Mircea: It is very much easy to set the multiple styles for an element in a single statement. It doesn't effect the existing properties and avoids the complexity of going for loops or plugins.

document.getElementById("demo").setAttribute(
   "style", "font-size: 100px; font-style: italic; color:#ff0000;");

BE CAREFUL: If, later on, you use this method to add or alter style properties, the previous properties set using 'setAttribute' will be erased.