Use this, and keep in mind:
For security reasons, Opera and
Mozilla will not allow you to access
the cssRules collection of a
stylesheet from another domain or
protocol. Attempting to access it will
throw a security violation error
function setStyleRule (selector, rule, sheetName) {
var sheets = document.styleSheets,
stylesheet = sheets[(sheets.length - 1)];
for( var i in document.styleSheets ){
if( sheets[i].href && sheets[i].href.indexOf(sheetName + ".css") > -1 ) {
stylesheet = sheets[i];
break;
}
}
if( stylesheet.addRule )
stylesheet.addRule(selector, rule);
else if( stylesheet.insertRule )
stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
}
Update – shorter code:
function getSetStyleRule(sheetName, selector, rule) {
var stylesheet = document.querySelector('link[href*=' + sheetName + ']')
if( stylesheet ){
stylesheet = stylesheet.sheet
stylesheet.insertRule(selector + '{ ' + rule + '}', stylesheet.cssRules.length)
}
return stylesheet
}
// Usage example
getSetStyleRule('main', 'body', 'background:red')