299

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 
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Mircea
  • 11,373
  • 26
  • 64
  • 95
  • 1
    What would `allMyStyle` be in your example? At the beginning you have a list of single variables... – Felix Kling Oct 19 '10 at 13:24
  • 1
    font-size:12px; left:200px; top:100px – Mircea Oct 19 '10 at 13:26
  • 1
    If this would work,it would be a string containing all the CSS to be set: document.getElementById("myElement").style = font-size:12px; left:200px; top:100px – Mircea Oct 19 '10 at 13:32
  • Interestingly though, it seems that applying multiple css rules in a sequence as opposed to using the cssText method, is faster: http://jsperf.com/csstext-vs-multiple-css-rules/4 – Andrei Oniga Mar 13 '12 at 07:24

28 Answers28

447

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.

Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 87
    document.getElementById("myElement").style.cssText +=';'+ cssString; will return a 'normalized' value for element.style.cssText- the new string will replace existing named properties with any new values, add new ones and leave the rest alone. – kennebec Oct 19 '10 at 15:45
  • 2
    @kennebec: Just tried it and you are right. I didn't know that, I just thought it appends to the already existing text. But it indeed replaces the values... – Felix Kling Oct 19 '10 at 15:55
  • 1
    I hoped somebody would get that and use it- I've never seen it documented. Good answer, by the way. – kennebec Oct 19 '10 at 20:19
  • 36
    @kennebec I've conducted a jsperf test and found that applying multiple css rules in a sequence as opposed to using the cssText method is faster: jsperf.com/csstext-vs-multiple-css-rules/4 – Andrei Oniga Mar 13 '12 at 07:25
  • 1
    what is cssString in this case? – Rohit Tigga Aug 22 '15 at 23:20
  • 2
    @RohitTigga: A string containing CSS rules. E.g. `display: block; position: absolute;`. – Felix Kling Aug 23 '15 at 03:28
  • 3
    Just in case you don't want to hit the link, I ran [the test from @AndreiOniga](http://jsperf.com/csstext-vs-multiple-css-rules/4) and *setting things explicitly (eg, `elem.style.width = '300px';`) was nearly an order of magnitude faster* than every alternative. So alternatives were 90% slower, and they were all give or take equally slow. – ruffin Dec 23 '15 at 22:26
  • @AndreiOniga @ruffin So even though this answer is the accepted answer, are you saying that you would be hard-pressed to find a scenario to use it? If I'm creating an element using `document.createElement()` and have 10+ style rules to set to it, it is better to have 10+ separate `.style.` lines than one line using `cssText`? – JoeL Aug 25 '16 at 14:57
  • How to use it? I try `document.querySelector('html').style = Object.assign({}, document.querySelector('html').style, { color: 'red'})` but nothing happen. – Jonathan Dion Apr 18 '17 at 02:21
  • @jonathandion: Assigning a new value to `style` doesn't seem to work (which makes sense since `style` itself is kind of magical). Assigning to properties of it works though: `Object.assign(document.querySelector('html').style, { color: 'red'})`, https://jsfiddle.net/4chz55dm/ . [See also Laimis answers](http://stackoverflow.com/a/34490573/218196). *edit:* I also just relased that you commented on that answer. Simply use the same code as in the answer. – Felix Kling Apr 18 '17 at 04:56
  • With this solution `cssString` looks like this: `var cssString = "font-size:"+fontsize+"left:"+left+";top:"+top;` || or simply: `var cssString = "font-size:12px;left:200px;top:100px"`; – eapo Sep 21 '19 at 18:34
386

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);
}
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Laimonas
  • 5,781
  • 2
  • 19
  • 20
  • 17
    sadly this method is not supported by IE11 http://kangax.github.io/compat-table/es6/#test-Object_static_methods_Object.assign – AndrewSilver Jul 28 '16 at 15:29
  • 5
    @AndrewSilver - Use babel && one of the many polyfill libraries to get support for ES6 features in non-compatible browsers. – Periata Breatta Oct 21 '16 at 08:48
  • 1
    When using babel, this is the method to go with! Perfect! – nirazul Mar 28 '17 at 08:20
  • 1
    @Nirazul How to use it? I try `document.querySelector('html').style = Object.assign({}, document.querySelector('html').style, { color: 'red'})` but nothing happen. – Jonathan Dion Apr 18 '17 at 02:23
  • 3
    This will suffice, as you expand a simple javascript object - No need to assign anything at all: `Object.assign(document.querySelector('html').style, { color: 'red' });` ...Just make sure that the style isn't overwritten in a lower element. This is very probable when using it on the `html` element. – nirazul Apr 18 '17 at 08:23
  • @Nirazul Thanks. I would like to have a better explanation. How the Node element update itself if you don't assign anything? – Jonathan Dion Apr 18 '17 at 11:12
  • @jonathandion There is no special magic at work. This is how javascript objects work. I suggest you read what `Object.assign` actually does: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign – nirazul Apr 18 '17 at 11:44
  • 1
    @Nirazul I understand now, my target was empty: Object.assign({}, document.querySelector('html').style, { color: 'red'}) vs Object.assign(document.querySelector('html').style, { color: 'red'}) – Jonathan Dion Apr 18 '17 at 13:39
  • this is the vanilla method i've been trying to figure out without having to create a separate helper function to just loop through properties – sm1215 Sep 21 '18 at 16:14
  • 2
    Caution! I think this will cause multiple repaints. At least, testing with a `Proxy` object, I found that `Object.assign` causes multiple calls to the `set` trap. – Quelklef Jul 16 '20 at 16:58
  • Interestingly, this doesn't work on Firefox (CSS2Properties doesn't have an indexed property setter for '0'). See https://stackoverflow.com/questions/46077237/how-to-solve-css2properties-doesnt-have-an-indexed-property-setter-for-0-erro – Petr L. Oct 07 '22 at 16:43
67

@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.

Community
  • 1
  • 1
SHANK
  • 2,978
  • 23
  • 31
49

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..

Ryan Kinal
  • 17,414
  • 6
  • 46
  • 63
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
19

I just stumbled in here and I don't see why there is so much code required to achieve this.

Add your CSS code using String Interpolation.

let styles = `
    font-size:15em;
    color:red;
    transform:rotate(20deg)`

document.querySelector('*').style = styles
a
Thielicious
  • 4,122
  • 2
  • 25
  • 35
  • 2
    I use this method too because it is useful if you don't have other inline styles, but sometimes it causes problems. – BaseScript Apr 20 '19 at 06:27
  • If problems occur then only due bad implementation. It all depends how, when and where you apply it to your code. – Thielicious Jan 27 '20 at 08:05
17

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];
}
Dan Mindru
  • 5,986
  • 4
  • 28
  • 42
Harmen
  • 22,092
  • 4
  • 54
  • 76
15

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");
eyupgevenim
  • 166
  • 2
  • 7
14

Strongly typed in typescript:

The object.assign method is great, but with typescript you can get autocomplete like this:

    const newStyle: Partial<CSSStyleDeclaration> =
    { 
        placeSelf: 'centered centered',
        margin: '2em',
        border: '2px solid hotpink'
    };

    Object.assign(element.style, newStyle);

Note the property names are camelCase not with dashes.

This will even tell you when they're deprecated.

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
6

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];
}
Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103
5

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

Jelan Maxwell
  • 51
  • 1
  • 2
4

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)

Spudley
  • 166,037
  • 39
  • 233
  • 307
  • 1
    That is not true, you can set all styles at once via `cssText`. – Felix Kling Oct 19 '10 at 13:26
  • 3
    @Felix: `cssText` is fine for setting the inline stylesheet value. However if you've also got classes, or if you only want to override some values but not all, it can be quite hard to use `cssText`. So you're right; you can do it, but I'd recommend against it for most use cases. – Spudley Oct 19 '10 at 13:57
  • 1
    Well having classes is no argument... `obj.top` or `obj.style.color` also justs sets the inline stylesheet value. And yes, in my answer I said that one would overwrite the values... it depends on the context if it is useful or not. – Felix Kling Oct 19 '10 at 14:34
  • 1
    You better make that obj=document.getElementById("myElement").style; or set your properties obj.style.top=top. – kennebec Oct 19 '10 at 15:12
  • @kennebec - hmm, could have sworn I did that. oh well, edited. thanks for spotting. – Spudley Oct 19 '10 at 16:00
3

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;
`;
Community
  • 1
  • 1
2

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);
dragonore
  • 783
  • 2
  • 11
  • 25
2

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];
}
groovecoder
  • 1,551
  • 1
  • 17
  • 27
Onkelborg
  • 3,927
  • 1
  • 19
  • 22
2

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);
nnevala
  • 5,779
  • 2
  • 20
  • 13
2

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)

Ryan Kinal
  • 17,414
  • 6
  • 46
  • 63
2

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.

const styles = {
  "font-size": "18px",
  "font-weight": "bold",
  "background-color": "lightgrey",
  color: "red",
  "padding": "10px !important",
  margin: "20px",
  width: "100px !important",
  border: "1px solid blue"
};

const elem = document.getElementById("my_div");

Object.entries(styles).forEach(([prop, val]) => {
  const [value, pri = ""] = val.split("!");
  elem.style.setProperty(prop, value, pri);
});
<div id="my_div"> Hello </div>
Siva K V
  • 10,561
  • 2
  • 16
  • 29
1

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.

Cedric Ipkiss
  • 5,662
  • 2
  • 43
  • 72
1

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;
});
Jalal
  • 3,308
  • 4
  • 35
  • 43
1

This is an old question but I thought it might be worthwhile to use a function for anyone not wanting to overwrite previously declared styles. The function below still uses Object.assign to properly fix in the styles. Here is what I did

function cssFormat(cssText){

   let cssObj = cssText.split(";");
   let css = {};
   
   cssObj.forEach( style => {

       prop = style.split(":");

       if(prop.length == 2){
           css[prop[0]].trim() = prop[1].trim();
       } 

   }) 
   
  return css;
}

Now you can do something like

let mycssText = "background-color:red; color:white;";
let element = document.querySelector("body");

Object.assign(element.style, cssFormat(mycssText));

You can make this easier by supplying both the element selector and text into the function and then you won't have to use Object.assign every time. For example

function cssFormat(selector, cssText){
  
   let cssObj = cssText.split(";");
   let css = {};
   
   cssObj.forEach( style => {

       prop = style.split(":");

       if(prop.length == 2){
           css[prop[0]].trim() = prop[1].trim();
       } 

   }) 

   element = document.querySelector(selector);
   
   Object.assign(element.style, css); // css, from previous code

} 

Now you can do:

cssFormat('body', 'background-color: red; color:white;') ;

//or same as above (another sample) 
cssFormat('body', 'backgroundColor: red; color:white;') ; 

Note: Make sure your document or target element (for example, body) is already loaded before selecting it.

teymzz
  • 33
  • 7
0

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

// styles to apply
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'
};

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

// create example paragraph and append it to the page body
const p = document.createElement('p');
p.textContent = 'This is a paragraph.';
document.body.appendChild(p);

// when the paragraph is clicked, call the function, providing the
// paragraph and myStyles object as arguments
p.onclick = (ev) => {
  applyStyles(p, myStyles);
}

// this time, target the page body and supply an object literal
applyStyles(document.body, {'background-color': 'grey'});
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
0

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

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)
V. Sambor
  • 12,361
  • 6
  • 46
  • 65
0

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

-1
<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>
Ru Chern Chong
  • 3,692
  • 13
  • 33
  • 43
-1

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.

-1

Is the below innerHtml valid

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

Different ways to achieve this:

1. document.getElementById("ID").style.cssText = "display:block; position:relative; font-size:50px";
2. var styles = {"display":"block"; "position":"relative"; "font-size":"50px"};
 
   var obj = document.getElementById("ID");
   Object.assign(obj.style, styles);

3. var obj = document.getElementById("ID");
obj.setAttribute("style", "display:block; position:relative; font-size:50px");

Hope this helps ~ RDaksh

Rahul Daksh
  • 212
  • 1
  • 7
-3
var styles = {
    "background-color": "lightgray",
    "width": "500px",
    "height": "300px"
};

/

var obj = document.getElementById("container");
Object.assign(obj.style, styles);
jasie
  • 2,192
  • 10
  • 39
  • 54
Aman Bansal
  • 53
  • 1
  • 6