Dynamically Add a CSS Class using Javascript

August 10th, 2006 Leave a comment Go to comments

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);

If you would like a reply to your comment, you must leave your email address! We receive dozens of questions every month from people who don't leave us with any way to contact them, so we have no choice but to ignore the question. We try to reply to as many questions as we can, if we know the email address of the person who asked the question. Thanks in advance for writing in :)

Allowed HTML: <b>, <i>, <em>, <strong>. All other < and > will be replaced with &lt; and &gt;.