1

now is 2020, and my target is chrome only. I want to check it on chrome only, so it is not same question. and my final goal is to avoid an infinite observe loop. this is my code:

.bg-gray-light {
    background-color: #fafbfc!important;
}
var e=document.querySelector('div.pagehead.bg-gray-light');
var z= e.style.getPropertyPriority('background-color'); // here is ''
var t=getComputedStyle(e).getPropertyPriority('background-color'); //here is '' too.

So how do I judge whether the background-color is '!important'.

FYI, I want to observe the style change and then change the style, but if it is !important, i need to force the change by e.style.setProperty(). To avoid the infinite observe loop, i can not just try to change the style. So i need to know whether the background-color is '!important'.

Rachid O
  • 13,013
  • 15
  • 66
  • 92
defend orca
  • 617
  • 7
  • 17
  • 1
    Does this answer your question, it includes a full function besides the getPropertyPriority? [Check if css property has !important attribute applied](https://stackoverflow.com/questions/10314131/check-if-css-property-has-important-attribute-applied) – imvain2 May 21 '20 at 18:40
  • i have read it, but my target is chrome, so is there more simple solution? – defend orca May 21 '20 at 18:43
  • i doubt anyone will notice if you manually set `#fafbfd` instead of `#fafbfc`, but you can easily detect the difference in JS to prevent infinite loops. – dandavis May 21 '20 at 18:59
  • @dandavis, just because change fail, so infinite loop, so i need check it before js code change the style. – defend orca May 21 '20 at 19:08

2 Answers2

3

I'm afraid that the getPropertyPriority method works on stylesheet rules only. After the browser rendered the dom, it's hard to find which rule has changed an specific element. The connection between element in dom and css rule is gone (in my opinion).

var declaration = document.styleSheets[0].cssRules[0].style;
var priority = declaration.getPropertyPriority("background-color");

See: MDN getPropertyPriority

Marc
  • 1,836
  • 1
  • 10
  • 14
0

thank you @dandavis, i have change my idea. i give up to check the '!important', i just try to change the style, but avoid infinite observe, like this:

observer.disconnect();
            e.style.setProperty(
                property,
                rgbstring,
                priority, //'important' or ''
            );
regist(observer,document);

and above code is not enough to avoid infinite observer, so we need cheek the value is need to set, especially don't change it again and again.

thanks @dandavis

defend orca
  • 617
  • 7
  • 17