jQuery CSS !important

Solution to jQuery CSS !important

Well, the typical way of getting !important will not work. Rather, you might want to try CSS DOM cssText. Hence, you will force !important to your jQuery statement by doing this.

1 jQuery('#id').css('cssText', 'height: 200px !important');

However, most people will be unfamiliar with cssText. cssText will overwrites the css of that particular element. Hence, you will have to redeclare the rule for that particular element all over again. On the other hand, if you are using JavaScript cssText, different browser treat cssText different such as ie you will define this way,

1 document.getElementById('id').style.cssText = 'height: 200px !important'

While normally you will use it this way.

1 document.getElementById('id').cssText = 'height: 200px !important'

Definitely, there is a better alternative such as using the cssRules/rules array which can specify the rule in that element to be modify.

The other more practical way of doing it is by introducing new class for your element. Instead of styling through jQuery or DOM object which is applying inline styling (means highest priority already), you should leave every majority styling or best all of the styling to an external style sheet that help you reduce some bytes on the script and also improve maintainability for both your code and style. You can do this using the toggleClass which adds a new class to that element automatically.

1 jQuery('#id').toggleClass('classname');

or you can do this in JavaScript by replacing the class (this is more efficient than the jQuery one since there isn’t any additional checking and stuff)

1 document.getElementById('id').className = 'classname';

Summary

Using !important in CSS is not advisable since it might kill your web usability. Furthermore, there is no reason why !important should be use as inline styling already has the highest priority. Hence, you might want to reconsider applying !important on your script after thinking about the consequences that might bought to your users.

你可能感兴趣的:(jQuery CSS !important)