ChatGPT解决这个技术问题 Extra ChatGPT

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.

Worth noting is that this actually works in Chrome (for me at least), but not in Firefox.
This also works for me in Chrome 17.x and Safari 5.1.1, but not in FF 8.0.
Doesn't work for me on Chromium 20.0.x using JQuery 1.8.2.
jQuery bug #11173 was about fixing .css and !important in jQuery core. The bug was closed as “won’t fix”. However, that bug’s test case was not as restrictive as the one in this question – the test case did not have an inline !important style it was trying to override. Thus, the proposed workaround in that bug will not work in this case.
Possible duplicate of Overriding !important with css or jquery -- While this one is older, and more highly voted, the other one's got the clearest, most valuable answer.

M
Makyen

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; }

$('#elem').addClass('importantRule');

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;' });

i am leaning toward your latter approach, but what is sad about it is that ill probably end up having to parse the previous cssText because i cant just discard it
ah, sorry couldn't get it, sometimes English humour goes beyond my understanding...:)
What's with the nested quotes ('"width: 100px !important"')? That didn't work for me, but when I removed the inner quotes it worked. Thanks!
small fix when style is empty: $('#elem').attr('style', function(i,s) { return (s||'') + 'width: 100px !important;' });
You should add @falko's fix, as in firefox your last snippet will set style to 'undefinedwidth: 100px !important;' when the current style is empty.
a
ashleedawg

I think I've found a solution. I've made it into a new function:

jQuery.style(name, value, priority);

You can use it to get values with .style('name') just like .css('name'), get the CSSStyleDeclaration with .style(), and also set values, with the ability to specify the priority as 'important'. See this.

Example

var div = $('someDiv');
console.log(div.style('color'));
div.style('color', 'red');
console.log(div.style('color'));
div.style('color', 'blue', 'important');
console.log(div.style('color'));
console.log(div.style().getPropertyPriority('color'));

Example output:

null
red
blue
important

The Function

(function($) {    
  if ($.fn.style) {
    return;
  }

  // Escape regex chars with \
  var escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  };

  // For those who need them (< IE 9), add support for CSS functions
  var isStyleFuncSupported = !!CSSStyleDeclaration.prototype.getPropertyValue;
  if (!isStyleFuncSupported) {
    CSSStyleDeclaration.prototype.getPropertyValue = function(a) {
      return this.getAttribute(a);
    };
    CSSStyleDeclaration.prototype.setProperty = function(styleName, value, priority) {
      this.setAttribute(styleName, value);
      var priority = typeof priority != 'undefined' ? priority : '';
      if (priority != '') {
        // Add priority manually
        var rule = new RegExp(escape(styleName) + '\\s*:\\s*' + escape(value) +
            '(\\s*;)?', 'gmi');
        this.cssText =
            this.cssText.replace(rule, styleName + ': ' + value + ' !' + priority + ';');
      }
    };
    CSSStyleDeclaration.prototype.removeProperty = function(a) {
      return this.removeAttribute(a);
    };
    CSSStyleDeclaration.prototype.getPropertyPriority = function(styleName) {
      var rule = new RegExp(escape(styleName) + '\\s*:\\s*[^\\s]*\\s*!important(\\s*;)?',
          'gmi');
      return rule.test(this.cssText) ? 'important' : '';
    }
  }

  // The style function
  $.fn.style = function(styleName, value, priority) {
    // DOM node
    var node = this.get(0);
    // Ensure we have a DOM node
    if (typeof node == 'undefined') {
      return this;
    }
    // CSSStyleDeclaration
    var style = this.get(0).style;
    // Getter/Setter
    if (typeof styleName != 'undefined') {
      if (typeof value != 'undefined') {
        // Set style property
        priority = typeof priority != 'undefined' ? priority : '';
        style.setProperty(styleName, value, priority);
        return this;
      } else {
        // Get style property
        return style.getPropertyValue(styleName);
      }
    } else {
      // Get CSSStyleDeclaration
      return style;
    }
  };
})(jQuery);

See this for examples of how to read and set the CSS values. My issue was that I had already set !important for the width in my CSS to avoid conflicts with other theme CSS, but any changes I made to the width in jQuery would be unaffected since they would be added to the style attribute.

Compatibility

For setting with the priority using the setProperty function, This Article says there is support for IE 9+ and all other browsers. I have tried with IE 8 and it has failed, which is why I built support for it in my functions (see above). It will work on all other browsers using setProperty, but it will need my custom code to work in < IE 9.


have you tested this on other browsers?
There is also the jQuery.important plugin that was published a couple years ago. I'm using it in production with only one minor issue (see their Issues tab.
$( '.someclass' ).each(function () { this.style.setProperty( 'border', 'none', 'important' ); }); stackoverflow.com/questions/11962962/… Simpler, cleaner and more efficient.
The only good way to deal with this is using classes, not direct style injection.
@Richard, the only good way to deal with this is not to use !important in your styles, at least for things you're going to change with jQuery... As long as they are your styles. If your code runs within a page coded by a student who works around his ignorance of specificity rules by slapping !important on every second style, you are going to ram head first into one of these !importants sooner or later.
N
Nick Craver

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');

ok, i used with as an example, what i care about is setting !important.
also i edited the question to reflect my situation better.. basically i have an external !important width that is set to something bad that i must override inline. width() does not work for this reason
@mkoryak - Updated with the only other non-class option, not sure if it'll fit your situation or not.
But it will override any other style directly applied to the element. stackoverflow.com/a/11723492/491044 is the easiest to implement.
prevent overrides by $('#elem').css('cssText', $('#elem').css('cssText')+'width: 100px !important'); concat it with the previous value
m
mkoryak
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.


This is one of the best answers. Simple and it works. And it doesn't require much explanation. It's just regular JavaScript, except for the jQuery selector. jQuery doesn't provide support for "important" so using regular JS is the way to go
If you wanna go Vanilla with it, just make var = document.getElementById('elem'); and perform the style methods on elem (as opposed to elem[0]). Cheers.
In vanilla JS, removeAttribute does not work. Do the following. var style = document.getElementById('elem'); style.removeProperty('width'); style.setProperty('width, '100px', 'important')
Also had problems with .removeAttribute. It seems to be an IE-only method. @mcoenca comment is right; .removeProperty works fine. It's IE9+ according to MSDN
@Dejan, sorry for very late answer, but this should work: elem.next().get(0).style...
C
Community

David Thomas’s answer describes a way to use $('#elem').attr('style', …), but warns that using it will delete previously-set styles in the style attribute. 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');

Here is a JS Bin demo.


addStyleAttribute() could also be modified to take the same parameters as jQuery’s .css(). For instance, it could support taking a map of CSS properties to their values. If you did that, you would basically be re-implementing .css() with the !important bug fixed but without any optimizations.
This worked well for me since the width was defined in a CSS class and I needed to override it dynamically with a value calculated based on the width of the browser window and content.
N
Nate

After reading other answers and experimenting, this is what works for me:

$(".selector")[0].style.setProperty( 'style', 'value', 'important' );

This doesn't work in IE 8 and under, though.


and since we still have to support IE8 (some of us, the unlucky) - this is not good.
P
Peter Mortensen

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.


the downside of this is that it will overwrite whatever cssText was in there before - so you cant really use it freely
anyway, you can use $("#elem").css("cssText", "+=;width: 100px !important;");
Don't forget you can use tilda string quotes to include variables: eg. element.css({ 'cssText': `top: ${xTop}px !important` });
m
mkoryak

Most of these answers are now outdated, IE7 support is not an issue.

The best way to do this that supports IE11+ and all modern browsers is:

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

Or if you want, you can create a small jQuery plugin that does this. This plugin closely matches jQuery's own css() method in the parameters it supports:

/**
 * Sets a CSS style on the selected element(s) with !important priority.
 * This supports camelCased CSS style property names and calling with an object 
 * like the jQuery `css()` method. 
 * Unlike jQuery's css() this does NOT work as a getter.
 * 
 * @param {string|Object<string, string>} name
 * @param {string|undefined} value
 */   
jQuery.fn.cssImportant = function(name, value) {
  const $this = this;
  const applyStyles = (n, v) => {
    // Convert style name from camelCase to dashed-case.
    const dashedName = n.replace(/(.)([A-Z])(.)/g, (str, m1, upper, m2) => {
      return m1 + "-" + upper.toLowerCase() + m2;
    }); 
    // Loop over each element in the selector and set the styles.
    $this.each(function(){
      this.style.setProperty(dashedName, v, 'important');
    });
  };
  // If called with the first parameter that is an object,
  // Loop over the entries in the object and apply those styles. 
  if(jQuery.isPlainObject(name)){
    for(const [n, v] of Object.entries(name)){
       applyStyles(n, v);
    }
  } else {
    // Otherwise called with style name and value.
    applyStyles(name, value);
  }
  // This is required for making jQuery plugin calls chainable.
  return $this;
};
// Call the new plugin:
$('#elem').cssImportant('height', '100px');

// Call with an object and camelCased style names:
$('#another').cssImportant({backgroundColor: 'salmon', display: 'block'});

// Call on multiple items:
$('.item, #foo, #bar').cssImportant('color', 'red');

Example jsfiddle here.


this is the answer. No need to check for other answers
c
chharvey

You can achieve this in two ways:

$("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
$("#elem").attr("style", "width: 100px !important");

Actually, the .prop() function was added in jQuery v1.6 and will work in Chrome... this is quoted from the prop page: Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
Not a very good idea for a generic solution. You might override your existing style using this.
P
Peter Mortensen

There's no need to go to the complexity of @AramKocharyan's answer, nor the need to insert any style tags dynamically.

Just overwrite style, but you don't have to parse anything, why would you?

// Accepts the hyphenated versions (i.e. not 'cssFloat')
function addStyle(element, property, value, important) {
    // Remove previously defined property
    if (element.style.setProperty)
        element.style.setProperty(property, '');
    else
        element.style.setAttribute(property, '');

    // Insert the new style with all the old rules
    element.setAttribute('style', element.style.cssText +
        property + ':' + value + ((important) ? ' !important' : '') + ';');
}

Can't use removeProperty(), because it won't remove !important rules in Chrome.
Can't use element.style[property] = '', because it only accepts camelCase in Firefox.

You could probably make this shorter with jQuery, but this vanilla function will run on modern browsers, Internet Explorer 8, etc.


P
Peter Mortensen

Here is what I did after encountering this problem...

var origStyleContent = jQuery('#logo-example').attr('style');
jQuery('#logo-example').attr('style', origStyleContent + ';width:150px !important');

Thank you, this is far simpler to implement than a custom plugin (even if it does potentially destroy other inline styles).
A
A J A Y

This solution doesn't override any of the previous styles, it just applies the one you need:

var heightStyle = "height: 500px !important";
if ($("foo").attr('style')) {
  $("foo").attr('style', heightStyle + $("foo").attr('style').replace(/^height: [-,!,0-9,a-z, A-Z, ]*;/,''));
else {
  $("foo").attr('style', heightStyle);
}

P
Peter Mortensen

If it is not so relevant and since you're dealing with one element which is #elem, you can change its id to something else and style it as you wish...

$('#elem').attr('id', 'cheaterId');

And in your CSS:

#cheaterId { width: 100px;}

why do you change the id to apply a css instead of just add a css class?
P
Peter Mortensen

The easiest and best solution for this problem from me was to simply use addClass() instead of .css() or .attr().

For example:

$('#elem').addClass('importantClass');

And in your CSS file:

.importantClass {
    width: 100px !important;
}

Since the width is computed in JavaScript this doesn't solve the problem.
S
Sebastian Zartner

Instead of using the css() function try the addClass() function:

  <script>
  $(document).ready(function() {
    $("#example").addClass("exampleClass");
  });
  </script>

  <style>
  .exampleClass{
    width:100% !important;
    height:100% !important;
  }
  </style>

The OP wrote that the value of the property is calculated dynamically, so your answer doesn't work for him.
This solution worked for me. I don't think I have the exact needs as the original poster but it does work where css() does not.
This is indeed a perfectly reasonable solution to a problem... just not this problem!
Á
Álvaro González

FYI, it doesn't work because jQuery doesn't support it. There was a ticket filed on 2012 (#11173 $(elem).css("property", "value !important") fails) that was eventually closed as WONTFIX.


P
Peter Mortensen

We need first to remove the previous style. I remove it using a regular expression. Here is an example for changing color:

var SetCssColorImportant = function (jDom, color) {
       var style = jDom.attr('style');
       style = style.replace(/color: .* !important;/g, '');
       jDom.css('cssText', 'color: ' + color + ' !important;' + style); }

Don't know why so many solutions hack a style tag onto the element when the cssText method works just fine... e.g. $selector.css('cssText','margin-bottom: 0 !important')
P
Peter Mortensen

An alternative way to append style in head:

$('head').append('<style> #elm{width:150px !important} </style>');

This appends style after all your CSS files so it will have higher priority than other CSS files and will be applied.


C
Community

May be it look's like this:

Cache

var node = $('.selector')[0];
OR
var node = document.querySelector('.selector');

Set CSS

node.style.setProperty('width', '100px', 'important');

Remove CSS

node.style.removeProperty('width');
OR
node.style.width = '';

P
Peter Mortensen

I think it works OK and can overwrite any other CSS before (this: DOM element):

this.setAttribute('style', 'padding:2px !important');

P
Peter Mortensen

Do it like this:

$("#elem").get(0).style.width= "100px!important";

S
Sebastian Luna

This solution will leave all the computed javascript and add the important tag into the element: You can do (Ex if you need to set the width with the important tag)

$('exampleDiv').css('width', '');
//This will remove the width of the item
var styles = $('exampleDiv').attr('style');
//This will contain all styles in your item
//ex: height:auto; display:block;
styles += 'width: 200px !important;'
//This will add the width to the previous styles
//ex: height:auto; display:block; width: 200px !important;
$('exampleDiv').attr('style', styles);
//This will add all previous styles to your item

P
Peter Mortensen

Three working examples

I had a similar situation, but I used .find() after struggling with .closest() for a long time with many variations.

The Example Code

// Allows contain functions to work, ignores case sensitivity

jQuery.expr[':'].contains = function(obj, index, meta, stack) {
    result = false;
    theList = meta[3].split("','");
    var contents = (obj.textContent || obj.innerText || jQuery(obj).text() || '')
    for (x=0; x<theList.length; x++) {
        if (contents.toLowerCase().indexOf(theList[x].toLowerCase()) >= 0) {
            return true;
        }
    }
    return false;
};

$(document).ready(function() {
    var refreshId = setInterval( function() {
        $("#out:contains('foo', 'test456')").find(".inner").css('width', '50px', 'important');
    }, 1000); // Rescans every 1000 ms
});

Alternative

$('.inner').each(function () {
    this.style.setProperty('height', '50px', 'important');
});

$('#out').find('.inner').css({ 'height': '50px'});

Working: http://jsfiddle.net/fx4mbp6c/


I will spare you a down vote but you should opt to replace the .indexOf() function with something that is more cross-browser compatible. Use, rather, .match() or .test() instead of .indexOf()
Why no semicolon in the line with var contents = ?
T
Tim Cutting

It may or may not be appropriate for your situation but you can use CSS selectors for a lot of these type of situations.

If, for example you wanted of the 3rd and 6th instances of .cssText to have a different width you could write:

.cssText:nth-of-type(3), .cssText:nth-of-type(6) {width:100px !important;}

Or:

.container:nth-of-type(3).cssText, .container:nth-of-type(6).cssText {width:100px !important;}

This does not match the 3rd and 6th instances of .cssText. :nth-of-type() does not do what you think it does. See here for an explanation.
Fair enough. I did read the link, but I'm not sure I have understood your point. Here's a fiddle showing this working as intended: jsfiddle.net/d2E4b
In your fiddle, you're dealing with a series of li elements. They are all of the same element type li, which is what the selector deals with. If you were to mix different elements in the same parent, then :nth-of-type() would behave differently, especially so once you add a class selector into the mix.
P
Peter Mortensen

I would assume you tried it without adding !important?

Inline CSS (which is how JavaScript adds styling) overrides the stylesheet CSS. I'm pretty sure that's the case even when the stylesheet CSS rule has !important.

Another question (maybe a stupid question but must be asked.): Is the element you are trying to work on display:block; or display:inline-block;?

Not knowing your expertise in CSS... inline elements don't always behave as you would expect.


css rules that have !important override everything, no matter where they are located, only exception being that inline styles with !important will override stylesheet styles with !important. This is the problem i am having. there is a stylesheet rule with !important that i would like to override. whats more, the value i need to supply must be computed through JS, so i cant simply change the stylesheet itself.
P
Peter Mortensen

We can use setProperty or cssText to add !important to a DOM element using JavaScript.

Example 1:

elem.style.setProperty ("color", "green", "important");

Example 2:

elem.style.cssText='color: red !important;'

A
Austin

I also discovered that certain elements or add-on's (like Bootstrap) have some special class cases where they do not play well with !important or other work-arounds like .addClass/.removeClass, and thus you have to to toggle them on/off.

For example, if you use something like <table class="table-hover">the only way to successfully modify elements like colors of rows is to toggle the table-hover class on/off, like this

$(your_element).closest("table").toggleClass("table-hover");

Hopefully this work-around will be helpful to someone! :)


P
Peter Mortensen

I had the same problem trying to change a text color of a menu-item when "event". The best way I found when I had this same problem was:

First step: Create, in your CSS, a new class with this purpose, for example:

.colorw{ color: white !important;}

Last step: Apply this class using the addClass method as follows:

$('.menu-item>a').addClass('colorw');

Problem solved.


Best answer, in my opinion. Most convenient one.
Thanks @Siyah CSS is known by loads of ppl but understood only for few and this is sad and makes some programmers to hate it lol
Not however if you want to generate CSS value with the js, forexample the color value defined in JS. Otherwise this is nice.
why would you want to define a color in js?
P
Peter Mortensen

The safest workaround to this is to add a class and then do the magic in CSS :-), addClass() and removeClass() should do the work.


R
Razan Paul

https://jsfiddle.net/xk6Ut/256/

An alternative approach is dynamically creating and updating CSS class in JavaScript. To do that, we can use style element and need to employ the ID for the style element so that we can update the CSS class

function writeStyles(styleName, cssText) {
    var styleElement = document.getElementById(styleName);
    if (styleElement) document.getElementsByTagName('head')[0].removeChild(
        styleElement);
    styleElement = document.createElement('style');
    styleElement.type = 'text/css';
    styleElement.id = styleName;
    styleElement.innerHTML = cssText;
    document.getElementsByTagName('head')[0].appendChild(styleElement);
}

...

  var cssText = '.testDIV{ height:' + height + 'px !important; }';
  writeStyles('styles_js', cssText)