JavaScript access CSS class by its name?
No, you can't access them by the selector - it's a simple list. You first had to build an index for it:
// assuming those are the right rules (ie from the right stylesheet)
var hui = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
var styleBySelector = {};
for (var i=0; i<hui.length; i++)
styleBySelector[hui[i].selectorText] = hui[i].style;
// now access the StyleDeclaration directly:
styleBySelector[".myclass"].color = "#ff0000";
Of course this is not a fool-proof method, there could be
- multiple selectors like
.myClass, .myOtherClass
- multiple occurences of one selector (though it doesn't matter, the last declaration overwrites previous styles anyway)
and instead of blindly assigning the color
property you first should check for existence of the declaration.