Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

css

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.

like image 595
Nathan Ridley Avatar asked Jul 31 '12 05:07

Nathan Ridley


1 Answers

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);
}​
like image 63
spliter Avatar answered Oct 26 '22 18:10

spliter