How to apply !important using .css()?

    |
  • Added:
  • |
  • In: Wordpress

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.

This Question Has 27 Answeres | Orginal Question | mkoryak

May be 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 = '';

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) 

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') 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 wont 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, IE8 etc

we can use setProperty or cssText to add !important to dom element using java script.

Eg1:

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

Eg2:

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

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

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

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

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> 

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

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

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.

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

I would assume you tried it without adding important?
inline css (which is how js adds styling) overrides 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, is it display:block; or display:inline-block; ?

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

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:

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

We need first remove previous style. I remove using a regular. I send you a example for change color,...

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

Kinda late but 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'); 

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 it's value.

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.

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.

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

3 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 contains fuction 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 1000ms }); 

Alternative

$( '.inner' ).each(function () { this.style.setProperty( 'height', '50px', 'important' ); }); $('#out').find('.inner').css({ 'height': '50px'}); 

Up vote if you found any use, thanks.

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

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

hope this helps, Sinan.

Why not just doing like this:

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

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

$('.selector').attr('style', 'width:500px !important'); 

I think I've found a real 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.

Demo

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

Here's the 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.

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 is:

1st step: Create, in your css, a new class with this purpose, for example:

.colorw{ color: white !important;} 

last step: Apply this class using addClass method as follows:

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

Problem solved. Hope it helps!

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


Search
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

NEED HOSTING?
Are you searching for Good Quality hosting?
You can Try It!
Connect Social With PHPAns
Top