Thursday, May 19, 2011

Altering CSS Class Attributes with JavaScript


This JavaScript function will dynamically change the style information for any CSS class in a Web Page. Applying this function to a class will cause all items calling on the class to change to the updated style value. This function works even if there are multiple stylesheets referenced in the document.
Function Name: changecss(theClass,element,value)
To use this function, copy this link and place it in the head of your HTML before any other JavaScript that may use it.
<script type="text/javascript" src="http://www.shawnolson.net/scripts/public_smo_scripts.js"></script>

Please include credit when using this script and read this site's Terms & Conditions before using.
This function was last updated on October 9, 2010. It has been tested and works in the following browsers:
  • Internet Explorer 6+ (Windows)
  • Firefox 3+ (Windows & Linux)
  • Google Chrome 2.0.172.33 + (Windows)
  • Safari 3.1.1 + (Windows)
  • Opera 9.64 +(Windows)
Note that I have tested these browsers on Windows; this function works in Firefox in Linux as well. I assume that the latest Mac versions work the same.


function changecss(theClass,element,value) {
    //Last Updated on October 10, 1020
    //documentation for this script at
    //http://www.shawnolson.net/a/503/altering-css-class-attributes-with-javascript.html
     var cssRules;

     var added = false;
     for (var S = 0; S < document.styleSheets.length; S++){

    if (document.styleSheets[S]['rules']) {
      cssRules = 'rules';
     } else if (document.styleSheets[S]['cssRules']) {
      cssRules = 'cssRules';
     } else {
      //no rules found... browser unknown
     }

      for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
       if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
        if(document.styleSheets[S][cssRules][R].style[element]){
        document.styleSheets[S][cssRules][R].style[element] = value;
        added=true;
        break;
        }
       }
      }
      if(!added){
      try{
          document.styleSheets[S].insertRule(theClass+' { '+element+': '+value+'; }',document.styleSheets[S][cssRules].length);

      } catch(err){
              try{document.styleSheets[S].addRule(theClass,element+': '+value+';');}catch(err){}

      }

      //if(document.styleSheets[S].insertRule){
              //document.styleSheets[S].insertRule(theClass+' { '+element+': '+value+'; }',document.styleSheets[S][cssRules].length);
            //} else if (document.styleSheets[S].addRule) {
                //document.styleSheets[S].addRule(theClass,element+': '+value+';');
            //}
      }
     }
    }
I hope it helped. Feel free to comment...