I have to access CSS class by name, and the code below works. However if I try hui[\"myclass\"]
or hui[\".myclass\"]
instead of hui[0]
To change the established rules, this is one approach:
// the [2] index is only because that's where JS Fiddle
// puts the user-entered CSS (from the CSS panel).
var sheets = document.styleSheets[2].rules,
classString = 'body',
props = ['color'], // requires a 1:1 relationship between two arrays...ugh
to = ['#0f0'];
for (var i = 0, len = sheets.length; i < len; i++) {
if (sheets[i].selectorText == classString) {
for (var c = 0, leng = props.length; c < leng; c++) {
sheets[i].style[props[c]] = to[c];
}
}
}
JS Fiddle demo.
And a slightly improved alternative (an object rather than two arrays, that require a 1:1 relationship):
var sheets = document.styleSheets[2].rules,
classString = 'body',
propsTo = {
'color': '#0f0'
};
for (var i = 0, len = sheets.length; i < len; i++) {
if (sheets[i].selectorText == classString) {
for (var prop in propsTo) {
if (propsTo.hasOwnProperty(prop)) {
sheets[i].style[prop] = propsTo[prop];
}
}
}
}
JS Fiddle demo.