The !important property, as you know, is applied immediately after the style property. For example,
div { display: none !important; color: red !important; }
I have defined !important to give importance to the values defined against each property. The properties are display and color.
You can apply !important property using inline style. For example,
<div style="color: Blue !important"> hello </div>
In the above example, no matter what color you have defined to the <div> element inside the <style> tag, or in your .css file, the color it will show is blue, since the color defined inline has an !important property.
Remember: The !important property is defined immediately after the style property and value and before the semicolon (;).
Now, let’s see how we can override the !important property in JavaScript.
Override !important property in JavaScript
In JavaScript, you can use the setAttribute() method to define attributes to an element. Using the same method, you can override the !important property of an element.
<!DOCTYPE html> <html> <head> <title>Overriding !imporant using JavaScript</title> <style> #d1 { display: none !important; color: red; } </style> </head> <body> <div id='d1'> hello </div> <input type='button' value='show' onclick='showElement();'> </body> <script> let showElement = () => { let ele = document.getElementById('d1'); ele.setAttribute ('style', 'display: block !important;'); } </script> </html>
In the above example, I have a <div> element whose display property is none and it also has the !important property. So, at the design time, I have decided to keep the <div> hidden.
#d1 { display: none !important; color: red; }
However later, for some reason now I have to show the element and therefore I had to override the !important property.
ele.setAttribute ('style', 'display: block !important;');
The setAttribute() method takes two parameters. The attribute style and the value, where I have defined !important with display property.
Using JavaScript setProperty() Method
Here’s another method that you can use. It’s the setProperty() method of the style property. For example, (the markup is the same as above)
<script> let ele = document.getElementById('d1'); ele.style.setProperty ('display', 'block', 'important'); </script>
The setProperty() method takes three parameters. The style property or the property name, the value for the property and finally the priority (which is !important). The last parameter in the method is optional, but we have used it.
Well, that’s it. Now you know how to override any style property like !important using JavaScript.