Nathan Ridley
Nathan Ridley

Reputation: 34396

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 I assign the value red !important, the value is ignored (i.e. not assigned).

const myStyleSheetRule = document.getElementById("stylesheet").sheet.cssRules[0];

myStyleSheetRule.style.borderTopColor = 'red'; // success
myStyleSheetRule.style.borderTopColor = 'red !important'; // fail
<style id="stylesheet">
  .box {
    display: inline-flex;
    border: 4px solid green;
    width: 100px;
    height: 100px;
    background: lightblue;
  }
</style>

<div class="box">gets red</div>
<div class="box" style="border-top-color: cyan">should also get red</div>

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.

Upvotes: 10

Views: 5324

Answers (3)

spliter
spliter

Reputation: 12569

Something like this should work:

const myStyleSheetRule = document.getElementById("stylesheet").sheet.cssRules[0];
const myStyleSheet = myStyleSheetRule.parentStyleSheet;

if (myStyleSheet.insertRule) {
  const l = myStyleSheet.cssRules.length;
  myStyleSheet.insertRule('.box {border-top-color: Red !important}', l);
} else {
  //IE
  myStyleSheet.addRule('.box', 'border-top-color: Red !important', -1);
}
<style id="stylesheet">
  .box {
    display: inline-flex;
    border: 4px solid green;
    width: 100px;
    height: 100px;
    background: lightblue;
  }
</style>

<div class="box">gets red</div>
<div class="box" style="border-top-color: cyan">is also red</div>

Upvotes: 3

gre_gor
gre_gor

Reputation: 6778

Use setProperty with the priority argument.

const myStyleSheetRule = document.getElementById("stylesheet").sheet.cssRules[0];

myStyleSheetRule.style.setProperty("border-top-color", "red", "important");
<style id="stylesheet">
  .box {
    display: inline-flex;
    border: 4px solid green;
    width: 100px;
    height: 100px;
    background: lightblue;
  }
</style>

<div class="box">gets red</div>
<div class="box" style="border-top-color: cyan">is also red</div>

Upvotes: 2

Jory Cunningham
Jory Cunningham

Reputation: 742

Try:

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

This will add it inline.

Upvotes: -2

Related Questions