Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

4 Answers

aashaykumar
You can set the width directly using .width() like this:

$("#elem").width(100);

Updated for comments: You have this option as well, but it'll replace all css on the element, so not sure it's any more viable:

$('#elem').css('cssText', 'width: 100px !important');
pankajshivnani123

const elem = $("#elem");
elem[0].style.removeAttribute('width');
elem[0].style.setProperty('width', '100px', 'important');

Note: Using Chrome may return an error such as:

elem[0].style.removeAttribute is not a function

Changing the line to use the .removeProperty function such as to elem[0].style.removeProperty('width'); fixed the issue.
akshay1995
Here is a way of using attr() without that problem:

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

As a function:

function addStyleAttribute($element, styleAttribute) {
$element.attr('style', $element.attr('style') + '; ' + styleAttribute);
}
addStyleAttribute($('#elem'), 'width: 100px !important');
kshitijrana14
You can do this:
$("#elem").css("cssText", "width: 100px !important;");

Using "cssText" as the property name and whatever you want added to the CSS as its value.

Login / Signup to Answer the Question.