Last updated: Mar 5, 2024
Reading timeยท2 min
Use the setProperty
method to override an element's !important styles.
The third parameter the method takes is the priority, which can be set to the
string important
.
Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <style> #box { display: none !important; background-color: orange !important; } </style> <body> <div id="box" style="width: 150px; height: 150px"> Hello world </div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const box = document.getElementById('box'); box.style.setProperty('display', 'block', 'important'); box.style.setProperty('background-color', 'lime', 'important');
We used the setProperty() method to set a new value for a property on the element's CSS style declaration object.
The method takes the following 3 parameters:
propertyName
- the name of the CSS property we want to modify. Note that
property names of multiple words must be hyphenated.value
- the new value for the CSS property.priority
- can be set to important
or an empty string.value
parameter must not contain !important
. The priority should be passed as the third parameter to the setProperty
method.If I load the page from the example above, I can see that we were able to
override the values of the display
and background-color
properties.
You can read the priority
of a specific CSS property by using the
getPropertyPriority
method.
const box = document.getElementById('box'); box.style.setProperty('display', 'block', 'important'); box.style.setProperty('background-color', 'lime', 'important'); // ๐๏ธ "important" console.log(box.style.getPropertyPriority('background-color')); // ๐๏ธ "lime" console.log(box.style.getPropertyValue('background-color')); // ๐๏ธ "lime" console.log(box.style.backgroundColor);
The
getPropertyPriority()
method returns a string that represents the priority of the property, e.g.
important
.
If the property doesn't have a priority set, an empty string is returned.
When using the getPropertyPriority()
and getPropertyValue()
methods, you
should pass multi-word CSS properties in hyphen case, whereas when accessing
properties on the style
object, you should use camel case.
You can learn more about the related topics by checking out the following tutorials: