Rate this script:  I Love it  /   I Hate it

Dynamic Modifcation of CSS Class Properties


Author: WSE
Website: http://www.webscriptexpert.com

Modifying the rendering of an element with an ID is relatively easy using document.getElementById. Modifying the attributes fo an entire class dynamically is a little more code, but the DOM does provide the means to do it through the stylesheet object; with some cross-browser variations.

Usage

copy n' paste!

Notice that the color of the text in the span is not changed, because the inline style prevails over the class in the stylesheet. This technique can be used to make on the fly changes to the look and feel of a page in response to events or user input.

Code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<title> Fragment</title>
<style type="text/css">
A.topLinks {font-weight:bold}
.Borders {font-weight:bold}
</style>
<script type="text/javascript">
function modRule()
{
        if (!document.styleSheets) return;
        var thecss = new Array();
        if (document.styleSheets[0].cssRules)  // Standards Compliant
        {
           thecss = document.styleSheets[0].cssRules;
        }
        else
        {         
           thecss = document.styleSheets[0].rules;  // IE
        }
        for (i=0;i<thecss.length;i++)
        {
           if ((thecss[i].selectorText.toLowerCase()=='a.toplinks') || (thecss[i].selectorText.toLowerCase()=='.borders'))
           {
             thecss[i].style.cssText="font-weight:normal; color:red";
           }
        }
}
</script>
</head>
<body>
<a href="#" class="topLinks" onclick="modRule();return false;">click here</a>
<div class="Borders"> hello world. <span style="color:blue">All of your bases are belong to us.</span> </div>
</body>
</html>
 

 

 
Dynamic Modifcation of CSS Class Properties scripts | Dynamic Modifcation of CSS Class Properties snippet | Dynamic Modifcation of CSS Class Properties example | Dynamic Modifcation of CSS Class Properties tutorial | Dynamic Modifcation of CSS Class Properties code