Skip to content Skip to sidebar Skip to footer

How To Add !important To A Stylesheet Rule Using Javascript?

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

Solution 1:

Something like this should work:

HTML

<div id="colored">?</div>​​​​​​​​​​​​​​​​​​​​​​​​​

Default stylesheet

#colored {
    border-top: 1px solid Black;
}​

Javascript

var all = document.styleSheets,
    s = all[all.length - 1],
    l = s.cssRules.length;

if (s.insertRule) {
    s.insertRule('#colored {border-top-color: Red !important}', l);
} else {
    //IE
    s.addRule('#colored', 'border-top-color: Red !important', -1);
}​

Solution 2:

This should make the trick;

var property='color';
varvalue='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*/);
    }

Solution 3:

Try:

myStyleSheetRule.setAttribute('style', 'border-top-color:red !important');

This will add it inline.

Post a Comment for "How To Add !important To A Stylesheet Rule Using Javascript?"