How to add! Important for a style sheet rule using JavaScript?

I have a reference to a CSSStyleRule object in JavaScript, and I want to update the style for border-top-color to red !important . If I set the value to red , there will be no problem. If I assign a value to red !important , the value is ignored (i.e. Not assigned).

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

How to set the flag of importance?

Note that this must be done using a style sheet rule that is available programmatically. In my use case, I cannot assign a style attribute or anything else. I am using Chrome on Windows 7.

+6
source share
2 answers

Something like this should work:

HTML

 <div id="colored">?</div>โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹ 

Default Style Sheet

 #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); }โ€‹ 
+4
source

Try:

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

This will add it to the string.

-2
source

Source: https://habr.com/ru/post/921733/


All Articles