javascriptcssgoogle-chromedomcssom

How can i use javascript to check if a css property has !important in chrome?


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'.


Solution

  • 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