How to add !important to CSS property with jQuery

In CSS !important is used to increase the priority of a CSS property. This ignores the overriding properties.

In jQuery, you can use the css() method to manipulate style property of the selector but this doesn’t allow to set !important to property.

For example –

$('#txt').css('width', '100px !important');

The above code doesn’t work when you run it.

In this tutorial, I show how you can add !important to CSS property with jQuery.

How to add !important to CSS property with jQuery


Contents

  1. Add class
  2. attr()
  3. cssText
  4. Conclusion

1. Add class

This adds a new class to the selector element and doesn’t replace the existing class from the element.

Call addClass() method on the selector and specify yours class-name in the method.

Syntax –

$( selector ).addClass( class-name );

Example

<style type='text/css'>
.textbox{
  width: 150px !important;
}
</style>
<script>
$(document).ready(function(){

    // Add .textbox class
    $("#txt").addClass('textbox');
});
</script>

2. 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(){
    $('#txt').attr('style', 'width: 150px !important');
});
</script>

This adds a new property to the element if it not specified otherwise ignores the existing property.


3. cssText

The cssText property allows setting multiple CSS styles or get the CSS style of selector as a string.

Set style Syntax –

$( selector ).css( { 'cssText', 'CSS style' } );

Example

<style type='text/css'>
.textbox{
  width: 150px !important;
}
</style>
<script>
$(document).ready(function(){

    // Change width
    $('#txt').css({
        'cssText': 'width: 220px !important'
    });
});
</script>

4. Conclusion

You can use any of the above-specified methods on your page to add !important to a property.

If you found this tutorial helpful then don't forget to share.