Search code examples
javascriptcssstylesheet

Prevent addRule from stripping !important


I am trying to make a jQuery plug-in that injects CSS rules onto the page. I am using addRule and insertRule. For some reason, addRule strips out !important from any rules you pass to it. Is there a way I can prevent it from doing so or a flag I can send to the function to mark the rule as important? I looked at the documentation for addRule but there was no mention of !important declarations.

document.getElementsByTagName('head')[0].appendChild(document.createElement('style'));
var sheet = document.styleSheets[document.styleSheets.length-1];
sheet.addRule('body','color: green !important');
h1 {
    color: yellow;
}
<h1>Test text</h1>

By the way, I am only using addRule for compatability with older versions of Internet Explorer. I am aware that insertRule is a more robust function.


Solution

  • I don't believe !important bubbles like you're expecting. !important lets rules take precedence over other rules with the same selector. Consider this example:

    <style>
    #me { color:blue !important; }
    </style>
    <p id='me'>Hello, World</p>
    <script>
    sheet.addRule('#me','color: green !important;');
    </script>
    

    You'll notice that #me should be blue by the stylesheet, but it's being overriden by the addRule.

    In your example, you're saying you want body color to percolate down to paragraphs, but !important is about choosing between rules with the same selector, not hierarchy. CSS Tricks has some words on this.