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?
The style property returns the values of an element's style attribute. The style property returns a CSSStyleDeclaration object. The CSSStyleDeclaration object contains all inline styles properties for the element. It does not contain any style properties set in the <head> section or in any external style sheets.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With