Forum Moderators: open
How can I dynamically change the property of a class in the style sheet?
I have a css file and html file like this as shown below. How can I dynamically change the font-color of all the titles on some mouse event.
Please help
Thanks
hrud.
style.css
---------
.folder{border:1px solid #black}
.title{font-size:14px; font-weight:bold;}
.content{font-size:12px;}
index.html
----------
<body>
<div class="folder">
<div class="title">header 1</div>
<div class="content">some content related to header1</div>
</div>
<div class="folder">
<div class="title">header 2</div>
<div class="content">some content related to header2</div>
</div>
<div class="folder">
<div class="title">header 3</div>
<div class="content">some content related to header3</div>
</div>
</body>
How can I dynamically change the property of a class in the style sheet?
... so that all the elements of a particular class will change, as opposed to the more traditional method of changing the styles of a particular element. Yeah, I too had been wondering about this...
In theory, this is possible in JavaScript through the styleSheets array, as in the following:
document.styleSheets[0].cssRules[1].style.color = 'red';
...and attach this to some onmouseover/onmouseout event.
The styleSheets[] array refers to all the linked (external) stylesheets and the embedded stylesheet. The cssRules[] array refers to the style rule within that stylesheet. The index of each array is by number only (the order in which they appear) - you can't refer to the stylesheet or rule by name. This in itself is a drawback, but there are numerous other browser incompatibilities that unfortunately make this method pretty much impossible to implement successfully cross-browser, certainly for anything more than a basic stylesheet.
FF and IE6 both at least support the styleSheets[] array. Opera8 doesn't! (Does Opera9?) cssRules[] is the W3C recommendation that FF adopts, but in IE6/7 it is called simply rules[]. And then the big big problem is that nearly every browser lists the rules differently in the rules array! So, trying to access the same rule in different browsers is pretty much impossible!
In practise, it's not really possible?! Anyone?
So, I guess you have to stick to the more traditional approach of perhaps traversing the DOM, looking for elements that have class="title" then either changing the style of the element directly, or perhaps the better method maybe to change the class of the element - in that way you keep the presentation in the CSS, out of the JavaScript.