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. 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. Conclusion

If you want to add !important to a property with jQuery then you can either use the addClass method or edit the style attribute.

I hope this tutorial helps you and if you find this useful then don’t forget to share.

 

Related Post

Spread the love
  • 2
  • 2
  •  
  •  
  • 2
  •  
  •  

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *