9

I know that to replace a single style, the code looks something like this:

myDOMElement.style.height = '400px';

But what if I want to completely replace the entire style object in one fell swoop, thereby speeding things up and avoiding redraws? For example, I would like to do this:

//Get the computed style
var computedStyle = window.getComputedStyle(myDOMElement);

//Change some stuff in that CSSStyleDeclaration without rendering
computedStyle.height = '10px';
computedStyle.width = '20px';
computedStyle.whatever = 'something';

//Apply the entirety of computedStyle to the DOM Element, thereby only redrawing once
myDOMElement.style = computedStyle;

However, when I run this code, my new style just gets ignored. What can I do to fix this?

AlexZ
  • 11,515
  • 3
  • 28
  • 42
  • 2
    Unfortunately, the `style` property is read-only. I'd look at a way to merge the `computedStyle` in – Phil Jan 09 '14 at 03:37
  • 3
    why not use css class? just add the class to the specified element. – Freedom Jan 09 '14 at 03:37
  • This might help you http://stackoverflow.com/questions/3968593/how-to-set-multiple-css-style-properties-in-javascript – skos Jan 09 '14 at 03:56

1 Answers1

6

You really don't want to use getComputedStyle("myElement") because versions of IE doesn't support it.

You can just append to the style attribute directly.

var myStyle = "color: #090";
document.getElementById("myElement").style.cssText += '; ' + myStyle; // to append
document.getElementById("myElement").style.cssText = myStyle; // to replace

myStyle can contain many css rules so you'll get them all in one redraw. As a bonus you get the added CSS Specificity Value of an inline style, which will override everything else but "!important".

jeremyjjbrown
  • 7,772
  • 5
  • 43
  • 55
  • Hey Jeremy, this is a really great solution that is definitely faster than simply replacing the properties individually! I cooked up a little speed test, and your solution is about 3 times faster on my browser (100x using your method is about 200ms, vs 600ms using the other method). Link to the speedtest below: http://codepen.io/azaslavsky/pen/ufHba – AlexZ Jan 10 '14 at 07:34
  • Glad to help! I like that codepen interface, it's very clean. – jeremyjjbrown Jan 10 '14 at 16:34
  • Thanks @jeremyjjbrown this helped me too, i was able to shorten for my situaation but .cssText worked a treat :) this.style.cssText = "cursor: pointer"; – Scott Sep 19 '14 at 10:32