There are a couple of ways we can use jQuery to add a CSS style as important. The best way we have found is to simply create a class that has the style with the !important property, and then add that class using the jQuery addClass() method.
$(".p1").addClass("permanent-red");
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 !important property and jQuery.
Here is our new HTML. It just has a new class, permanent-red, in the style section.
This is a paragraph.
And here is the jQuery code:
$(".p1").addClass("permanent-red");
Here would be the result:
This is a paragraph.
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery(".p1").addClass("permanent-red");
Note that we can also do this just using pure JavaScript.
There is also a way we can add a new style and update it all using jQuery.
jQuery CSS Important – Updating CSS Style and HTML All in jQuery
In this example, instead of updating the CSS style section and adding a new class to it, we will create the class using jQuery and add it to our HTML.
We will do this by creating a new style tag with our class in it, and adding it to the head section of our document using the jQuery appendTo() method.
Here is the jQuery code to do this:
$("").appendTo("head");
$(".p3").addClass("permanent-orange");
So here is our HTML code again with a new class name:
This is a paragraph.
Here is the code for you to see:
This is a paragraph.
And this is what happens when we apply our jQuery code from above:
This is a paragraph.
Let’s take a look at one final way that we can use jQuery CSS important that we don’t really recommend.
Adding a CSS !important property using the jQuery attr() method
Another way we can easily use jQuery to add a CSS style as !important, is by using the jQuery attr() method and targeting the style attribute.
We don’t recommend this because doing it this way will get rid of any other in-line styles the element might have. We have included it though because it is an easy way to add a style to an element if it has no other inline styles attached to it.
So here is our HTML again with inline styles this time:
This is a paragraph.
Here is the code for you to see:
This is a paragraph.
And here is our simple jQuery code using the attr() method:
$(".p5").attr("style", "color: red !important");
And this is what happens when we apply our jQuery code from above:
This is a paragraph.
As you can see in this example, the text used to have a bold style attached to it, but this has been overwritten using the jQuery code.
Hopefully this article has been useful for you to understand how to use jQuery to add a CSS style as important.