You must assign some required styles to the elem element you just created using JavaScript. Since these properties are absolutely obligatory and it is impossible to allow their redefinitions in any way, it was decided to use the !important directive.

 elem.style.color = "red !important"; 

However, this does not work. Having rummaged on the Internet I found out that it is possible to set an !important property only through the cssText property (well, or through setAtribute ).

 elem.style.cssText = "color: red !important;"; 

So, like, really works. However, I do not understand why, after such an installation, it is possible to override the value of a property:

 elem.style.color = "green"; // работает! Текст действительно становится зеленым. Хотя, по идее, не должен. 

Moreover, it is not clear to me why even in the absence of the !important property it is not possible to override this property in the .css file.

 let elem = document.querySelector("#test"); elem.style.color = "red"; 
 #test { color: green; } 
 <div id="test">Hello</div> 

Please explain.

    2 answers 2

    The fact is that if you do so

     elem = document.getElementById("id1"); elem.style.color = "green"; 
     <div id="id1">hallow</div> 

    That color is written in the inner style element.
    Run, click F12 and see what happened.

     <div id="id1" style="color: green;">hallow</div> 

    And the inner style always has the highest priority, and is not subject to any class overrides. Except if class is set important .

     .class1 { color: red; } .class2 { color: red !important; } 
     <div class="class1" style="color:green">Привет</div> <div class="class2" style="color:green">Привет</div> 

    • Ahhh! For sure! Just flew out of my head. Then, it turns out, and !important not needed at all ... - smellyshovel
    • And what about this: However, I do not understand why after such a setup it is possible to override the value of a property ? - smellyshovel
    • @smellyshovel redefinition is possible either through the class with important, in this case, use Cyril's answer. Or via JS, in this case the inner style overwritten. - Dmitry Polyanin
    • in this case, the inner style will overwrite - well, I see it. He asked why. Well, thanks anyway. - smellyshovel
    • @smellyshovel I did not understand your question, why, please explain? - Dmitry Polyanin
     elem.style.setProperty("color", "red", "important"); 

    setProperty

    Several properties at once:

     elem.setAttribute("style", "color:red!important;font-size:20px!important"); 
    • Thank! I did not know about the existence of such an API. However, specifically in my case will not work, since I need to set several properties at once. But I still have in mind. - smellyshovel