In CSS !important is used to increase the based on the priority of a CSS property. This ignores the overriding some properties.
How to add !important to CSS property with jQuery?
Contents
In jQuery, you can use the simple css() method to manipulate style property of the selector but this doesn’t allow to set !important to property.
For example – how to apply !important in javascript?
$('#unicodedata').css('width', '100px !important');
The above source code doesn’t work when you run it.
In this article, I learn to how you can add !important to CSS property with jQuery & JavaScripts.
1. Using Add class
This adds a included new class to the using selector HTML element as well as doesn’t replace the existing CSS class from the HTML element.
Here simply, Call addClass() method on the jquery selector and custom yours CSS your-class-name in the method.
Add class selector Syntax –
$( selector ).addClass( your-class-name );
Example : How to include !important in jquery?
<style type='text/css'> .custom-mycl{ width: 245px !important; } </style> <script> $(document).ready(function(){ // Add .custom-mycl class $("#unicodedata").addClass('custom-mycl'); }); </script>
Also Read: How to get the class name using Jquery Example with demo?
2. Using attr()
This method gets or sets the value of the element attribute.
Syntax –
//Get attribute value $( selector ).attr( 'Attribute-name' ); //Set attribute value $( selector ).attr( 'Attribute-name', value );
Example :
Using attr() to edit element style attribute and specifying value with !important.
<script> $(document).ready(function(){ $('#unicodedata').attr('style', 'width: 245px !important'); }); </script>
This adds a new property to the element if it not specified otherwise ignores the existing property.
3. Using cssText
The pure cssText some property supports setting multiple based CSS styles as well as get the applay CSS style of any html selector as a data string.
Set style Syntax –
$( selector ).css( { 'cssText', 'YOUR Custom CSS style' } );
Example : How to apply !important using .css()?
<style type='text/css'> .custom-mycl{ width: 245px !important; } </style> <script> $(document).ready(function(){ // Update width $('#unicodedata').css({ 'cssText': 'width: 220px !important' }); }); </script>
I am Jaydeep Gondaliya , a software engineer, the founder and the person running Pakainfo. I’m a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, JavaScript, jQuery, Laravel, CodeIgniter, VueJS, AngularJS and Bootstrap from the early stage.