How to add !important to CSS property with jQuery

In CSS !important is use 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.

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

You can simply add a new class to the selector element and this doesn’t replace existing class in the selector.

Simply 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

It always a good idea to put !important to a property when another selector CSS rules affect the element.

You can do this in jQuery either by altering style attribute or add a new class to the selector.

Spread the love

Related Post

Be First to Comment

Leave a Reply

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