Add CSS !important Declarations Using jQuery

css_important_declaration

While using jQuery and CSS, in some cases we need to use css important declarations using jQuery. CSS important declarations are help to override the parent css rules from a particular child object. For example, a list have a font size of 14px and font-weight of bold with red color and we need to change the third child element of the list object’s font size to 10px, font-weight to normal and color of the text to be blue. This can be done with CSS like given below.

ul li{
  font-size:14px;
  font-weight:bold;
  color:red;
}
ul li.blue{
  font-size:10px !important;
  font-weight:normal !important;
  color:blue !important;
}

In some cases we need to use the CSS important declarations with jQuery. The normal method of applying  CSS rules using jQuery is given below.

  $('.listClassName').css('font-size','10px');

If we attach the important declaration with the font size will through the error in jQuery. Then how to ?
Find the method from below.

  $('.listClassName').css('cssText','font-size:10px !important;');

The above code will apply css inline code ‘ font-size:10px !important;’ to an element which have the class name of ‘listClassName’. Enjoy.

Share with Friends
[Facebook] [Jamespot] [Reddit] [StumbleUpon] [Twitter] [Email]

Leave a Reply

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