Javascript – How to apply !important using .css()


I am having trouble applying a style that is !important. I’ve tried:

$("#elem").css("width", "100px !important");

This does nothing; no width style whatsoever is applied. Is there a jQuery-ish way of applying such a style without having to overwrite cssText (which would mean I’d need to parse it first, etc.)?

Edit: I should add that I have a stylesheet with an !important style that I am trying to override with an !important style inline, so using .width() and the like does not work since it gets overridden by my external !important style.

Also, the value that will override the previous value is computed, so I cannot simply create another external style.

Best Solution

The problem is caused by jQuery not understanding the !important attribute, and as such fails to apply the rule.

You might be able to work around that problem, and apply the rule by referring to it, via addClass():

.importantRule { width: 100px !important; }


Or by using attr():

$('#elem').attr('style', 'width: 100px !important');

The latter approach would unset any previously set in-line style rules, though. So use with care.

Of course, there's a good argument that @Nick Craver's method is easier/wiser.

The above, attr() approach modified slightly to preserve the original style string/properties, and modified as suggested by falko in a comment:

$('#elem').attr('style', function(i,s) { return (s || '') + 'width: 100px !important;' });