Hi I need to get input for a css class font-size attribute from the user like 8px,10px,12px and so on.. and dynamically I need to change it.

I get the following code from net

function changecss(theClass,element,value) {
    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) {
           alert(document.styleSheets[S][cssRules][R].selectorText);
        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+';');
            //}
      }
     }
    }

Its working fine in mozilla, but in IE 8 and IE 9 it works but affects some other styles also and after onclick the div it set to correct.Please help me.If anyone knows better than this suggest me.

Anandhikrishnan,

Dynamically rewriting a stylesheet is not generally the preferred approach. It is complex (as evidenced by the code you posted) and not always reliable (as you have found).

It is far easier to change the style properties of all elements currently styled with the relevant style direcitve. A potential downside of this approach is that relevant dom elements added in the future also need to be managed in the same way, though this seldom problematic; you just need to be disciplined when writing your code.

If you really must play around with stylesheets then you will find it easier dynamically to insert new directive(s) into an already included stylesheet or (I think) a fresh one (itself dynamically inserted). Normal cascading rules apply such that later/more-specific/!important) styles override earlier/less-specific/not-important ones.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.