This post will discuss how to apply a CSS rule with !important declaration to an HTML element using jQuery.

The .css() method ignores the !important declaration. Therefore, you can’t directly set a CSS property with the !important declaration using the .css() method.

Edit in JSFiddle

 
However, there are several alternatives in jQuery to apply a CSS rule with !important declaration to an HTML element.

1. Set cssText property

The cssText property is used to set the element’s inline style declaration. When used with the .css() method, the !important declaration works. But be careful with this approach as this would replace any style modification you have previously performed in the HTML style attribute or through jQuery’s .css() method.

Edit in JSFiddle

2. Set style attribute

Here, the idea is to apply the CSS style with the !important declaration using the style attribute. With jQuery, you can easily set the style attribute using the .attr() method. This approach has the same issues as the previous method that it would replace any previously set styles on the style attribute.

Edit in JSFiddle

3. Create a CSS rule in stylesheet

Here, the idea is to create a CSS style with !important declaration in your stylesheet and apply that style to the element. With jQuery, we can use the addClass() method to apply the class to an element.

JS


CSS



Edit in JSFiddle

4. Create a CSS rule in <style> element

Another approach is to create a CSS rule with !important declaration in a <style> element and append that style to the document head. With jQuery, you can use the .append() method to append the <style> element to end of the <head> element.

Edit in JSFiddle

That’s all about applying a CSS rule with !important declaration using jQuery.