DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Roy has posted 10 posts at DZone. View Full User Profile

Dynamic Modification Of CSS Class Properties

  • submit to reddit
        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.  

For additional CSS and HTML see some of the full length articles
<a href=""> Written by IT professionals</a> from Experts Round Table

<title> Fragment</title>
<style type="text/css">
A.topLinks {font-weight:bold}
.Borders {font-weight:bold}
<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;
           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";
<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>

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.