How to manipulate styles with javascript

March 15th, 2012

In the DOM the document has a styleSheets property which is a StyleSheetList object, which is a collection of CSSStyleSheet objects which has a cssRules property which is a CSSRuleList object which is a collection of CSSStyleRule objects.

alert(document.styleSheets[0].cssRules[0].cssText)

And the  CSSStyleRule has a cssText property which gives a CSS rule declaration like

body{background-color:white;}
The StyleSheetList and the CSSRuleList are array like objects, but like domNodeList you can’t call foreach methods on it but they are enumable with a loop. Each style tag or link tag to an external  stylesheet is created as a seperate StyleSheetList object. That does make sense, but sometimes one big array of rules can come in hand to. This is the code to achieve that. We use some tricks like calling the splice method to  list to create arrays.
var rules = Array(),superCSSSheet='';

Array.prototype.slice.call(document.styleSheets).forEach(function(sheet){

 rules = rules.concat(Array.prototype.slice.call(sheet.cssRules))

 })

rules.forEach(function(rule){
superCSSSheet += rule.cssText+"\n"
})
alert(superCSSSheet)

Which clearly shows WordPress isn’t very efficient with CSS code: to be more specific most themes and plugin aren’t 🙂

Another funny thing came to attention is that CSS color values are read out differently then set.

Comments are closed.