Override an Element's !important Styles using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 5, 2022

banner

Check out my new book

Override an Element's !important Styles using JavaScript #

Use the setProperty method to override an element's !important styles, e.g. box.style.setProperty('display', 'block', 'important'). The third parameter the method takes is the priority, which can be set to the string important.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <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.

index.js
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:

  1. propertyName - the name of the CSS property we want to modify. Note that property names of multiple words must be hyphenated.
  2. value - the new value for the CSS property
  3. priority - can be set to important or empty string.
The 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.

override important style

You can read the priority of a specific CSS property by using the getPropertyPriority method.

index.js
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 does not 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.
Use the search field on my Home Page to filter through my more than 3,000 articles.