[javascript] 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 

This question is related to javascript coding-style

The answer is


Your best bet may be to create a function that sets styles on your own:

var setStyle = function(p_elem, p_styles)
{
    var s;
    for (s in p_styles)
    {
        p_elem.style[s] = p_styles[s];
    }
}

setStyle(myDiv, {'color': '#F00', 'backgroundColor': '#000'});
setStyle(myDiv, {'color': mycolorvar, 'backgroundColor': mybgvar});

Note that you will still have to use the javascript-compatible property names (hence backgroundColor)


Don't think it is possible as such.

But you could create an object out of the style definitions and just loop through them.

var allMyStyle = {
  fontsize: '12px',
  left: '200px',
  top: '100px'
};

for (i in allMyStyle)
  document.getElementById("myElement").style[i] = allMyStyle[i];

To develop further, make a function for it:

function setStyles(element, styles) {
  for (i in styles)
    element.style[i] = styles[i];
}

setStyles(document.getElementById("myElement"), allMyStyle);

See for .. in

Example:

var myStyle = {};
myStyle.fontsize = "12px";
myStyle.left= "200px";
myStyle.top= "100px";
var elem = document.getElementById("myElement");
var elemStyle = elem.style;
for(var prop in myStyle) {
  elemStyle[prop] = myStyle[prop];
}

This is old thread, so I figured for anyone looking for a modern answer, I would suggest using Object.keys();

var myDiv = document.getElementById("myDiv");
var css = {
    "font-size": "14px",
    "color": "#447",
    "font-family": "Arial",
    "text-decoration": "underline"
};

function applyInlineStyles(obj) {
    var result = "";
    Object.keys(obj).forEach(function (prop) {
        result += prop + ": " + obj[prop] + "; ";
    });
    return result;
}

myDiv.style = applyInlineStyles(css);

There are scenarios where using CSS alongside javascript might make more sense with such a problem. Take a look at the following code:

document.getElementById("myElement").classList.add("newStyle");
document.getElementById("myElement").classList.remove("newStyle");

This simply switches between CSS classes and solves so many problems related with overriding styles. It even makes your code more tidy.


Since strings support adding, you can easily add your new style without overriding the current:

document.getElementById("myElement").style.cssText += `
   font-size: 12px;
   left: 200px;
   top: 100px;
`;

You can write a function that will set declarations individually in order not to overwrite any existing declarations that you don't supply. Let's say you have this object parameter list of declarations:

const myStyles = {
  'background-color': 'magenta',
  'border': '10px dotted cyan',
  'border-radius': '5px',
  'box-sizing': 'border-box',
  'color': 'yellow',
  'display': 'inline-block',
  'font-family': 'monospace',
  'font-size': '20px',
  'margin': '1em',
  'padding': '1em'
};

You might write a function that looks like this:

function applyStyles (el, styles) {
  for (const prop in styles) {
    el.style.setProperty(prop, styles[prop]);
  }
};

which takes an element and an object property list of style declarations to apply to that object. Here's a usage example:

const p = document.createElement('p');
p.textContent = 'This is a paragraph.';
document.body.appendChild(p);

applyStyles(p, myStyles);
applyStyles(document.body, {'background-color': 'grey'});

_x000D_
_x000D_
// styles to apply_x000D_
const myStyles = {_x000D_
  'background-color': 'magenta',_x000D_
  'border': '10px dotted cyan',_x000D_
  'border-radius': '5px',_x000D_
  'box-sizing': 'border-box',_x000D_
  'color': 'yellow',_x000D_
  'display': 'inline-block',_x000D_
  'font-family': 'monospace',_x000D_
  'font-size': '20px',_x000D_
  'margin': '1em',_x000D_
  'padding': '1em'_x000D_
};_x000D_
_x000D_
function applyStyles (el, styles) {_x000D_
  for (const prop in styles) {_x000D_
    el.style.setProperty(prop, styles[prop]);_x000D_
  }_x000D_
};_x000D_
_x000D_
// create example paragraph and append it to the page body_x000D_
const p = document.createElement('p');_x000D_
p.textContent = 'This is a paragraph.';_x000D_
document.body.appendChild(p);_x000D_
_x000D_
// when the paragraph is clicked, call the function, providing the_x000D_
// paragraph and myStyles object as arguments_x000D_
p.onclick = (ev) => {_x000D_
  applyStyles(p, myStyles);_x000D_
}_x000D_
_x000D_
// this time, target the page body and supply an object literal_x000D_
applyStyles(document.body, {'background-color': 'grey'});
_x000D_
_x000D_
_x000D_


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);
}

With ES6+ you can use also backticks and even copy the css directly from somewhere:

_x000D_
_x000D_
const $div = document.createElement('div')
$div.innerText = 'HELLO'
$div.style.cssText = `
    background-color: rgb(26, 188, 156);
    width: 100px;
    height: 30px;
    border-radius: 7px;
    text-align: center;
    padding-top: 10px;
    font-weight: bold;
`

document.body.append($div)
_x000D_
_x000D_
_x000D_


You can have individual classes in your css files and then assign the classname to your element

or you can loop through properties of styles as -

var css = { "font-size": "12px", "left": "200px", "top": "100px" };

for(var prop in css) {
  document.getElementById("myId").style[prop] = css[prop];
}

We can add styles function to Node prototype:

Node.prototype.styles=function(obj){ for (var k in obj)    this.style[k] = obj[k];}

Then, simply call styles method on any Node:

elem.styles({display:'block', zIndex:10, transitionDuration:'1s', left:0});

It will preserve any other existing styles and overwrite values present in the object parameter.


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.

_x000D_
_x000D_
let styles = `_x000D_
    font-size:15em;_x000D_
    color:red;_x000D_
    transform:rotate(20deg)`_x000D_
_x000D_
document.querySelector('*').style = styles
_x000D_
a
_x000D_
_x000D_
_x000D_


Simplest way for me was just using a string/template litteral:

elementName.style.cssText = `
                                width:80%;
                                margin: 2vh auto;
                                background-color: rgba(5,5,5,0.9);
                                box-shadow: 15px 15px 200px black; `;

Great option cause you can use multiple line strings making life easy.

Check out string/template litterals here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals


I think is this a very simple way with regards to all solutions above:

const elm = document.getElementById("myElement")

const allMyStyle = [
  { prop: "position", value: "fixed" },
  { prop: "boxSizing", value: "border-box" },
  { prop: "opacity", value: 0.9 },
  { prop: "zIndex", value: 1000 },
];

allMyStyle.forEach(({ prop, value }) => {
  elm.style[prop] = value;
});

Please consider the use of CSS for adding style class and then add this class by JavaScript classList & simply add() function.

style.css

.nice-style { 
fontsize : 12px; 
left: 200px;
top: 100px;
}

script JavaScript

const addStyle = document.getElementById("myElement"); addStyle.classList.add('nice-style');


Use CSSStyleDeclaration.setProperty() method inside the Object.entries of styles object.
We can also set the priority ("important") for CSS property with this.
We will use "hypen-case" CSS property names.

_x000D_
_x000D_
const styles = {_x000D_
  "font-size": "18px",_x000D_
  "font-weight": "bold",_x000D_
  "background-color": "lightgrey",_x000D_
  color: "red",_x000D_
  "padding": "10px !important",_x000D_
  margin: "20px",_x000D_
  width: "100px !important",_x000D_
  border: "1px solid blue"_x000D_
};_x000D_
_x000D_
const elem = document.getElementById("my_div");_x000D_
_x000D_
Object.entries(styles).forEach(([prop, val]) => {_x000D_
  const [value, pri = ""] = val.split("!");_x000D_
  elem.style.setProperty(prop, value, pri);_x000D_
});
_x000D_
<div id="my_div"> Hello </div>
_x000D_
_x000D_
_x000D_


set multiple css style properties in Javascript

document.getElementById("yourElement").style.cssText = cssString;

or

document.getElementById("yourElement").setAttribute("style",cssString);

Example:

document
.getElementById("demo")
.style
.cssText = "margin-left:100px;background-color:red";

document
.getElementById("demo")
.setAttribute("style","margin-left:100px; background-color:red");

A JavaScript library allows you to do these things very easily

jQuery

$('#myElement').css({
  font-size: '12px',
  left: '200px',
  top: '100px'
});

Object and a for-in-loop

Or, a much more elegant method is a basic object & for-loop

var el = document.getElementById('#myElement'),
    css = {
      font-size: '12px',
      left: '200px',
      top: '100px'
    };  

for(i in css){
   el.style[i] = css[i];
}

Using plain Javascript, you can't set all the styles at once; you need to use single lines for each of them.

However, you don't have to repeat the document.getElementById(...).style. code over and over; create an object variable to reference it, and you'll make your code much more readable:

var obj=document.getElementById("myElement").style;
obj.top=top;
obj.left=left;

...etc. Much easier to read than your example (and frankly, just as easy to read as the jQuery alternative).

(if Javascript had been designed properly, you could also have used the with keyword, but that's best left alone, as it can cause some nasty namespace issues)


Is the below innerHtml valid

_x000D_
_x000D_
var styleElement = win.document.createElement("STYLE");_x000D_
styleElement.innerHTML = "#notEditableVatDisplay {display:inline-flex} #editableVatInput,.print-section,i.fa.fa-sort.click-sortable{display : none !important}";
_x000D_
_x000D_
_x000D_


<button onclick="hello()">Click!</button>

<p id="demo" style="background: black; color: aliceblue;">
  hello!!!
</p>

<script>
  function hello()
  {
    (document.getElementById("demo").style.cssText =
      "font-size: 40px; background: #f00; text-align: center;")
  }
</script>

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.