There are a couple of ways we can add a CSS style as important using JavaScript. The best way we have found is to simply use the Style setProperty() method and target a specific style attribute.
document.getElementById("p1").style.setProperty("color", "red", "important");
If we wanted to do this to a div that only had a class and not an id, we could use the querySelector() method.
document.querySelector(".p1").style.setProperty("color", "red", "important");
Let’s see this in action below.
Let’s say we have the following HTML:
This is a paragraph.
Here is the code for you to see:
This is a paragraph.
Now let’s use our code from above to change the color of the text to red using the setProperty() method.
And here is the JavaScript code:
document.getElementById("p1").style.setProperty("color", "red", "important");
Here would be the result:
This is a paragraph.
Note this can also be done using jQuery.
Let’s look at one more way that we can add a CSS style as !important using JavaScript
Another Way to Add the CSS Important Property to an Element Using JavaScript
Another way we can add a CSS style as important using JavaScript is to create a class that has the style with the !important property, and then add that class using JavaScript with the help of the add() method.
document.getElementById("p3").classList.add("permanent-red");
Or if we wanted to target a class again:
document.querySelector(".p3").classList.add("permanent-red");
Let’s say we have the following HTML:
This is a paragraph.
Here is the code for you to see:
This is a paragraph.
Now let’s use our code from above to change the color of the text to red using the !important property and JavaScript.
Here is our new HTML. It just has a new class, permanent-red, in the style section.
This is a paragraph.
And here is our JavaScript code:
document.querySelector(".p3").classList.add("permanent-red");
Here would be the result:
This is a paragraph.
Hopefully this article has been useful for you to understand how to add a CSS style as important in JavaScript.