How to add !important to a stylesheet rule using JavaScript?

Viewed 4750

I've got a reference to a CSSStyleRule object in JavaScript and I want to update the style for border-top-color to red !important. If I assign the value red, no problems occur. If I assign the value red !important, the value is ignored (i.e. not assigned).

myStyleSheetRule.style.borderTopColor = 'red'; // success
myStyleSheetRule.style.borderTopColor = 'red !important'; // fail

How do I set the !important flag?

Note that it has to be done via a stylesheet rule accessed programatically. In my use case, I can't assign a style attribute or anything else. I'm using Chrome on Windows 7.

3 Answers

This should make the trick;

var property='color';
var value='red !important'; 
var selector='h1';

if(value.indexOf("!important") > 0){
           var newRule=myStyleSheetRule.style.cssText+" "+property+":"+value;
           myStyleSheetRule.insertRule(selector + " { " + newRule + "; }",/*indexOfTheRule*/);            
           myStyleSheetRule.deleteRule(/*indexOfTheRule*/);
    }
Related