Tested to work with IE9, Chrome and Opera. I had a problem with this when I wrote it, so I decided that instead of changing the existing rules, I would simply add a new rule after the existing ones. From memory, the problem was in the default browser found in Android 2.3
Changing an existing rule seemed to be a better (cleaner) solution, although adding new rules ultimately turned out to be the chosen way. (I changed the background images by creating canvas images, and then setting the background-image property. Images can be quite large, hence the preference for updating)
Function
function replaceRuleAttrib(ruleSelector, attribText, newValue) { var nSheets, nRules, sheetNum, curSheet, curStyle, curAttrib; var nSheets = document.styleSheets.length; if (nSheets == 0) document.head.appendChild(document.createElement('style')); else for (sheetNum = 0; sheetNum<nSheets; sheetNum++) { curSheet = document.styleSheets[sheetNum]; nRules = curSheet.cssRules.length; for (ruleNum=0; ruleNum<nRules; ruleNum++) { curRule = curSheet.cssRules[ruleNum]; if (curRule.selectorText == ruleSelector) { for (styleI=0; styleI<curRule.style.length; styleI++) { styleName = curRule.style[styleI]; styleVal = curRule.style[styleName]; if (styleName == attribText) { curRule.style[styleName] = newValue; return true; } } } } } document.styleSheets[0].insertRule( ruleSelector+'{' + attribText + ": " + newValue + "; }", 0); }
CSS Example (formerly)
<style> h1 { color: red; } </style>
Application:
function onHeadingClick() { replaceRuleAttrib('h1', 'color', 'green'); }
CSS example (after)
<style> h1 { color: green; } </style>
source share