Dynamically Add a CSS Class using Javascript
Posted in CSS on August 10, 2006
0
I was writing a module for a webapp today and was thinking how cool it would be if I could dynamically add CSS classes using Javascript. At that particular moment, I had all the classes for all the modules grouped together in one big file, but since sometimes I didn't load all the modules, it was inefficient.
It took me a while to find some examples on doing this, so figured I would post the function I wrote in case anyone else has this same problem.
function addCSSclass(className, classRule) { if (document.all) { document.styleSheets[0].addRule("." + className, classRule) } else if (document.getElementById) { document.styleSheets[0].insertRule("." + className + " { " + classRule + " }", 0); } }