Apply a CSS rule with !important declaration using jQuery
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.
|
1 2 3 |
$(document).ready(function() { $('input').css('width', '200px !important'); // this won't work }); |
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.
|
1 2 3 |
$(document).ready(function() { $('input').css('cssText', 'width: 200px !important'); }); |
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.
|
1 2 3 |
$(document).ready(function() { $('input').attr('style', 'width: 200px !important'); }); |
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
|
1 2 3 |
$(document).ready(function() { $('input').addClass('inputWidth'); }); |
CSS
|
1 2 3 |
.inputWidth { width: 200px !important; } |
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.
|
1 2 3 |
$(document).ready(function() { $('head').append('<style> input { width: 200px `!important` } </style>'); }); |
That’s all about applying a CSS rule with !important declaration using jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)