0

How could I detect !important rule of style property for directed DOM element?

ex:

<div class = "class">
***content***
</div>

.class{
top: 45px!important; 
}

let elmStyles = document.getElementsByClassName('class')[0].style;
/* i need this =====> */  let isImportant = elmStyles.getPropertyPriority("top");

I`ve found some info about that, but I can not apply it for concrete DOMelement https://developer.mozilla.org/ru/docs/Web/API/CSSStyleDeclaration/getPropertyPriority

echo_54
  • 1
  • 1
  • `CSSStyleDeclaration` operates on the _declaration_ level, nomen est omen, you can not “apply” that for a specific DOM element. – CBroe Apr 16 '20 at 13:39
  • You can perhaps try and get all declarations that apply to the element first, https://stackoverflow.com/questions/2952667/find-all-css-rules-that-apply-to-an-element - but I guess then you would still have to figure out which actually apply based on specificity, if multiple rules set a value for the same property. – CBroe Apr 16 '20 at 13:41

1 Answers1

0

You can find all the elements to which top and that particular class which .class is applied to

Means you need to loop through all the rules and find the corresponding class for it

var declaration = document.styleSheets;
for(var i=0;i<declaration.length;i++) {
    for(var j=0;j<declaration[i].cssRules.length;j++) {
        var rule = declaration[i].cssRules[j];
        if(rule.style.getPropertyPriority("top")=="important") {
            var selector = rule.selectorText;
            if(selector[0]==".") {
                var elements = document.getElementsByClassName(selector.substring(1));
                for(var k=0;k<elements.length;k++) {
                    var element = elements[k];
                    console.log(element)
                }
            }
        }
    }
}

this loop will loop through all rules and find top is marked as !important

Then select all elements to which the class is applied and print in the console

Currently I have written only for class, for ID and tag name this is code will not work

Dickens A S
  • 3,824
  • 2
  • 22
  • 45