How to apply !important using .css()?
Asked Answered
T

31

857

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.

Transponder answered 16/4, 2010 at 20:31 Comment(9)
Worth noting is that this actually works in Chrome (for me at least), but not in Firefox.Mellott
This also works for me in Chrome 17.x and Safari 5.1.1, but not in FF 8.0.Tremann
Doesn't work for me on Chromium 20.0.x using JQuery 1.8.2.Mashburn
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.Kreutzer
If you don't care about IE 8 and under, see this: https://mcmap.net/q/53605/-how-to-apply-important-using-cssRiddle
I've opened jQuery bug #2837 to get this fixed. Hopefully that one won't get closed for no good reason.Employee
... aaand jQuery have decided that they won't fix this bug because "just use a plugin". Yay for open source.Employee
After stranded on this SO answer i decided to remind me on this xkcd.com/912 and use less again :/Carin
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.Dunite
T
35

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.

Transponder answered 27/11, 2019 at 15:4 Comment(0)
H
737

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;' });
Hydrophone answered 16/4, 2010 at 20:40 Comment(14)
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 itTransponder
@ricebowl np, i made a quick test, what you're saying unfortunately won't work in this example. Browsers put a higher priority to styles which are defined to an ID rather than a class. see. sinan.kodingen.com/csstest.htmlPheasant
@Pheasant Y., I was rather foolishly, and optimistically, hoping that there wasn't a contradictory rule set in the ID-related rules. I was also hoping, to be entirely honest, that !important would override those that were (unless they were also specified with !important). Still, at least my final '@Nick Craver's method is easier/wiser' holds true! ^.^Hydrophone
btw Nick Craver's method is no different than yours...:) just another way of writing it with jquery... changing style attribute or changing cssText with jquery's css method does exactly the same thing.Pheasant
@Pheasant Y., yeah, I know; I was just being all self-deprecating and English about it... =bHydrophone
ah, sorry couldn't get it, sometimes English humour goes beyond my understanding...:)Pheasant
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!Mellott
A variation on the attr() solution without the problem of unsetting previously-set inline style rules.Kreutzer
small fix when style is empty: $('#elem').attr('style', function(i,s) { return (s||'') + 'width: 100px !important;' });Bradshaw
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.Zepeda
the last method worked for me, but I had to add a preceding ; to the style I wanted to add .. for whatever reason, even though the original element's inline style had the attribute closure, it wasn't coming through in sZenaidazenana
This should be the absolute answer as the previous, accepted solution, is a rather nasty hack typical of jquery code, seen all too often.Resonant
You should also add @falko's fix for IE too as it shows 'undefinedwidth: 100px !important;' on there too. (IE11 to be specific).Bullion
if later you want to remove the !important of the same element using the same method you can use s.replace('width: 100px !important;', '')Uncanonical
C
344

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.

Corri answered 17/1, 2012 at 12:23 Comment(14)
have you tested this on other browsers?Transponder
See my updates, I've built support for IE8 and lower, and it works fine in IE9 (as stated in the links) and of course all other browsers.Corri
Ah, I didn't test it in IE6, but surely IE7 has superseded it there :)Corri
See #9009794Detinue
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.Capias
Sadly, this solution does not work in IE8 running in IE7 compatibility mode, as CSSStyleDeclaration is not available.Adverb
CSSStyleDeclaration.prototype.getPropertyValue returns undefined in IE8, not null. The IE8 polyfill did not work until I changed null to undefined (I actually check for both just to be safe...).Goodygoody
Also, text.replace(...) falls apart if text isn't... text. For example, I was getting 0 (an int) in text, and this issue was solved by editing the Regex.escape function to return (text + '').replace(...).Goodygoody
$( '.someclass' ).each(function () { this.style.setProperty( 'border', 'none', 'important' ); }); #11963462 Simpler, cleaner and more efficient.Cureton
The only good way to deal with this is using classes, not direct style injection.Koester
@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.Dingo
@Dingo Few years passed since your comment, please go and tell them Bootstrap 4 people what you said... They have classes to add borders, and they all have !important in the stylesheet.Guereza
The best answer is to use the attr() propetry as @David Thomas suggested.Inky
Works like a charm! I'm not sure I completely agree with the use of attr() as the "best" answer - it is at least "pure vanilla" jquery, but it is rather ridiculous to have to type $('#elem').attr('style', function(i,s) { return (s || '') + 'width: 100px !important;' }); and to not be able to set a particular style attribute that has already been set with it.Scrambler
I
161

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');
Incisure answered 16/4, 2010 at 20:32 Comment(5)
ok, i used with as an example, what i care about is setting !important.Transponder
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 reasonTransponder
@Transponder - Updated with the only other non-class option, not sure if it'll fit your situation or not.Incisure
But it will override any other style directly applied to the element. https://mcmap.net/q/53605/-how-to-apply-important-using-css is the easiest to implement.Getup
prevent overrides by $('#elem').css('cssText', $('#elem').css('cssText')+'width: 100px !important'); concat it with the previous valueEvslin
B
95
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.

Byway answered 13/9, 2013 at 18:18 Comment(7)
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 goSalo
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.Illimitable
In vanilla JS, removeAttribute does not work. Do the following. var style = document.getElementById('elem'); style.removeProperty('width'); style.setProperty('width, '100px', 'important')Maldives
Also had problems with .removeAttribute. It seems to be an IE-only method. @Maldives comment is right; .removeProperty works fine. It's IE9+ according to MSDNSelfrighteous
How to apply styling to next() node? elem[0].next().style... dosn't work.Humility
@Dejan, sorry for very late answer, but this should work: elem.next().get(0).style...Albers
elem[0].style.removeAttribute is not a functionYear
G
58

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.

Guglielmo answered 30/7, 2012 at 14:24 Comment(2)
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.Kreutzer
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.Residence
T
35

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.

Transponder answered 27/11, 2019 at 15:4 Comment(0)
R
34

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.

Riddle answered 2/8, 2014 at 23:33 Comment(1)
and since we still have to support IE8 (some of us, the unlucky) - this is not good.Transponder
D
30

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.

Doublecheck answered 13/9, 2014 at 1:20 Comment(3)
the downside of this is that it will overwrite whatever cssText was in there before - so you cant really use it freelyTransponder
anyway, you can use $("#elem").css("cssText", "+=;width: 100px !important;");Neurasthenic
Don't forget you can use tilda string quotes to include variables: eg. element.css({ 'cssText': `top: ${xTop}px !important` });Unexacting
C
19

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");
Catima answered 9/7, 2015 at 11:13 Comment(2)
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.Quartering
Not a very good idea for a generic solution. You might override your existing style using this.Mathamathe
V
14

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.

Vassar answered 4/10, 2013 at 0:56 Comment(0)
I
13

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');
Ible answered 15/5, 2013 at 8:54 Comment(1)
Thank you, this is far simpler to implement than a custom plugin (even if it does potentially destroy other inline styles).Cisneros
H
9

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);
}
Hussey answered 8/10, 2012 at 17:12 Comment(0)
L
9

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;
}
Ladew answered 16/3, 2016 at 15:40 Comment(1)
Since the width is computed in JavaScript this doesn't solve the problem.Sachsse
P
8

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;}
Pheasant answered 16/4, 2010 at 22:1 Comment(1)
why do you change the id to apply a css instead of just add a css class?Halfcocked
F
8

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>
Fakir answered 24/11, 2014 at 8:47 Comment(3)
The OP wrote that the value of the property is calculated dynamically, so your answer doesn't work for him.Pickens
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.Shalne
This is indeed a perfectly reasonable solution to a problem... just not this problem!Transponder
B
7

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.

Baziotes answered 16/3, 2016 at 15:59 Comment(0)
D
6

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); }
Dieldrin answered 8/4, 2013 at 11:2 Comment(2)
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')Rosiarosicrucian
@Rosiarosicrucian Bu the cssText will replace the existing styles within it,Teahouse
C
6

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.

Caravaggio answered 10/7, 2013 at 5:49 Comment(0)
S
6

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 = '';
Streusel answered 19/5, 2015 at 13:20 Comment(0)
S
6

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

this.setAttribute('style', 'padding:2px !important');
Shivaree answered 3/10, 2017 at 11:35 Comment(0)
H
5

Do it like this:

$("#elem").get(0).style.width= "100px!important";
Hegemony answered 10/9, 2013 at 16:44 Comment(0)
A
5

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
Ante answered 6/5, 2018 at 16:30 Comment(0)
S
4

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/

Somersomers answered 19/6, 2017 at 18:8 Comment(2)
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()Lanell
Why no semicolon in the line with var contents = ?Grath
E
3

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.

Entresol answered 16/4, 2010 at 20:58 Comment(1)
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.Transponder
W
3

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;}
Watch answered 30/8, 2013 at 12:35 Comment(3)
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.Agonize
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/d2E4bWatch
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.Agonize
S
3

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;'
Strychninism answered 22/8, 2016 at 10:8 Comment(0)
E
2

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! :)

Eisler answered 2/6, 2014 at 20:31 Comment(0)
O
2

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.

Own answered 14/3, 2017 at 14:7 Comment(2)
Not however if you want to generate CSS value with the js, forexample the color value defined in JS. Otherwise this is nice.Heliostat
why would you want to define a color in js?Own
G
1

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

Gerigerianna answered 20/4, 2018 at 11:23 Comment(0)
D
0

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)
Demagnetize answered 26/8, 2016 at 0:54 Comment(0)
N
-6

Another easy method to solve this issue adding the style attribute:

$('.selector').attr('style', 'width:500px !important');
Nonstriated answered 21/4, 2014 at 13:52 Comment(1)
The problem with this solution is that it would replace any other styles in the style attribute instead of just changing/adding the width property.Fib

© 2022 - 2024 — McMap. All rights reserved.