The DOM will replace the entire style attribute (CSSStyleDeclaration) with the element

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

myDOMElement.style.height = '400px'; 

But what if I want to completely replace the entire style object with one fell swoop, thereby speeding up work and avoiding redrawing? 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 is simply ignored. What can I do to fix this?

+7
javascript dom css
source share
1 answer

You really do not want to use getComputedStyle ("myElement") because IE versions do not support it.

You can simply add a 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 get them all in one redraw. As a bonus, you get the added CSS specificity value of the inline style that will override everything else, but "important."

+4
source share

All Articles