I know that to replace a single style, the code looks something like this:
myDOMElement.style.height = '400px';
But what if I want to pletely 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 puted style
var putedStyle = window.getComputedStyle(myDOMElement);
//Change some stuff in that CSSStyleDeclaration without rendering
putedStyle.height = '10px';
putedStyle.width = '20px';
putedStyle.whatever = 'something';
//Apply the entirety of putedStyle to the DOM Element, thereby only redrawing once
myDOMElement.style = putedStyle;
However, when I run this code, my new style just gets ignored. What can I do to fix this?
I know that to replace a single style, the code looks something like this:
myDOMElement.style.height = '400px';
But what if I want to pletely 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 puted style
var putedStyle = window.getComputedStyle(myDOMElement);
//Change some stuff in that CSSStyleDeclaration without rendering
putedStyle.height = '10px';
putedStyle.width = '20px';
putedStyle.whatever = 'something';
//Apply the entirety of putedStyle to the DOM Element, thereby only redrawing once
myDOMElement.style = putedStyle;
However, when I run this code, my new style just gets ignored. What can I do to fix this?
Share Improve this question asked Jan 9, 2014 at 3:29 AlexZAlexZ 12.1k3 gold badges29 silver badges43 bronze badges 3-
2
Unfortunately, the
style
property is read-only. I'd look at a way to merge theputedStyle
in – Phil Commented Jan 9, 2014 at 3:37 - 3 why not use css class? just add the class to the specified element. – Freedom Commented Jan 9, 2014 at 3:37
- This might help you stackoverflow./questions/3968593/… – skos Commented Jan 9, 2014 at 3:56
1 Answer
Reset to default 6You 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".