JavaScript access CSS class by its name?

css, javascript, properties

Solution

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.

Problem

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]` it cannot find it. ``` function change_class() { var hui = document.styleSheets[0].rules || document.styleSheets[0].cssRules; hui[0].style["color"] = "#ff0000" } ``` ``` .myclass { color: #00aa00; } ``` ``` <div class="myclass" onclick="change_class()">Some Text</div> ``` EDIT: I need to be able to acess as i described on line 1 i dont want to acess trough individual elements on page, but directly to stylesheet by class name. So you all saying i cannot access to stylesheet by class name only by index?

Original source