16 Mar

addRule bug in IE6

If you use the addRule() function in IE6 to add a style element, then be aware that IE6 does not seem to understand the usage of commas in selectors. It will return an “invalid argument” error.

In CSS, the comma in a selector is used to say “the following styles apply to each of these comma-delimited items”. So, for example. a,h1{text-decoration:underline} should underline anchors and header-ones.

Here is a function to add rules for both IE and Firefox. It took me fifteen minutes of debugging to figure out the comma bug, but that’s fixed in the below code.

function addRule(rule){
 if(document.styleSheets&&document.styleSheets.length){
  var a=document.styleSheets[0],arr=rule.replace(/}.*/,'').split('{'),arr2,i;
  if(a.insertRule)a.insertRule(rule,0);
  else if(a.addRule){
   arr2=arr[0].split(/,/);
   for(i=0;i<arr2.length;i++)a.addRule(arr2[i],arr[1]);
  }
 }
}

The above is called like this: addRule('a,h1{text-decoration:underline}'); in JavaScript. At the moment, it requires that a stylesheet be attached, but that requirement can easily be hacked away.