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.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
.myclass {
color: #00aa00;
}
</style>
<script type="text/javascript">
function change_class() {
var hui = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
hui[0].style["color"]="#ff0000"
}
</script>
</head>
<body>
<div class="myclass" onclick="change_class()">Some Text</div>
</body>
</html>
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?
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
.myClass, .myOtherClass
and instead of blindly assigning the color
property you first should check for existence of the declaration.
Yes, Bergi is right:
You first have to build an index for the style list.
BUT take care:
If there is more than 1 stylesheet you first have to loop over the stylesheets.
So I like to improve Bergis solution:
var styleBySelector = {};
for (var j=0; j<document.styleSheets.length; j++) {
var styleList = document.styleSheets[j].rules || document.styleSheets[j].cssRules;
for (var i=0; i<styleList.length; i++)
styleBySelector[styleList[i].selectorText] = styleList[i].style;
}
// And then invoke or set the style you wish like this:
styleBySelector[".myStyle"].color = "#ff0000";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With