Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM replace entire style attribute (CSSStyleDeclaration) on element

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?

like image 957
AlexZ Avatar asked Jan 09 '14 03:01

AlexZ


People also ask

Which property sets or returns the value of the style attribute of an element?

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.


1 Answers

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

like image 163
jeremyjjbrown Avatar answered Sep 19 '22 15:09

jeremyjjbrown