How to Apply !Important Using .Css()

How to apply !important using .css()?

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.

Using CSS !important with JavaScript

Try this code using CSSStyleDeclaration.setProperty():

function myFunction() {
var x = document.querySelectorAll("#testDiv p.example");
x[0].style.setProperty("background-color", "red", "important");
}

Adding !important with jQuery

Best way is to create a new CSS style with margin !important and add the CSS to the element.

CSS:

.zeroMargin { margin: 0 !important; }

and then in JS:

myEm.css({"position":"fixed", "top":"50px", "left":"50px"}).addClass('zeroMargin');

Alternatively, You can also do that entirely with JS using cssText

myEm.css("cssText", "margin:0 !important;position:fixed;top:50px;left:50px;"});

This is equivalent to setting the style.cssText property of that element. So you may not need an !important in that case..

To preserve you can use a function like below,

$('#cssTest').css('cssText', function(i, v) {  return this.style.cssText + ';border-color: blue !important;';});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><div id="cssTest" style="border: 1px solid red !important; width: 100px; height: 100px;"></div>

Overriding !important with css or jquery

Here you go:

$( '.someclass' ).each(function () {
this.style.setProperty( 'border', 'none', 'important' );
});

Live demo: http://jsfiddle.net/Gtr54/

The .setProperty method of an element's style object enables you to pass a third argument which represents the priority. So, you're overriding an !important value with your own !important value. As far as I know, it is not possible to set the !important priority with jQuery, so your only option is the built-in .setProperty method.

How to include !important in jquery

Apparently it's possible to do this in jQuery:

$("#tabs").css("cssText", "height: 650px !important;");

Src: http://bugs.jquery.com/ticket/2066

Overriding !important style

I believe the only way to do this it to add the style as a new CSS declaration with the '!important' suffix. The easiest way to do this is to append a new <style> element to the head of document:

function addNewStyle(newStyle) {
var styleElement = document.getElementById('styles_js');
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = 'styles_js';
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
styleElement.appendChild(document.createTextNode(newStyle));
}

addNewStyle('td.EvenRow a {display:inline !important;}')

The rules added with the above method will (if you use the !important suffix) override other previously set styling. If you're not using the suffix then make sure to take concepts like 'specificity' into account.

Apply !important CSS style to div, not children

If I understood your goal correct, you can do it by inheriting parent background-color property

.rwui_type_note,.rwui_type_note p {  background-color: #FFDC1E !important;  /*Needs to be important to override defaults*/  color: black !important;}
.panelContent p { background-color: inherit !important;}
<div class="rwui_text_box rwui_text_small  rwui_type_note  rwui_id_caebfd70-f9c3-489b-9f95-c01c1aa13f36 ">  <span class="rwui_icon rwui_iconfont_note"></span>  <span class="rwui_content rwui_body rwui_has_icon ">        <p>Text in a Note UI Box</p>        <div class="panel" style="background-color: white;border-color: orange;border-width: 1px;">            <div class="panelContent" style="background-color: white;">                <p>Text in a Panel - user set to white background</p>            </div>        </div>    </span></div>

Using !important in jQuery's css() function

Dont apply styles to a class. Apply a class to your div as a style!

Let jQuery do all the work for you

You style sheet should have these classes in them

.ui-widget-overlay  {
position: absolute;
left: 8px;
top: 9px;
width: 518px !important;
}

.ui-widget-small { height: 985px; }

.ui-widget-full { height: 1167px; }

Ok thats your CSS sorted

now your div

 <div id="myWidget" class="ui-widget-overlay ui-widget-small"> YOUR STUFF </div>

Now you can use jQuery to manipulate your divs either by attaching to a button/click/hover whatever it is you wanna use

$('#myWidget').removeClass('ui-widget-small').addClass('ui-widget-full')

And you dont need to use !important - that is really used when you start having issues with large CSS files or several loaded styles.

This is instant but you can also add an effect

$('#myWidget').hide('slow', function(){ $('#myWidget').removeClass('ui-widget-small').addClass('ui-widget-full').show('slow') }  )

You can add styles dynamically to your page like this- and to replace all existing classes with another class, we can use .attr('class', 'newClass') instead.

$('body').prepend('<style type="text/css"> .myDynamicWidget { height: 450px; } </style>')
$('#myWidget').attr('class', 'ui-widget-overlay')
$('#myWidget').addClass('myDynamicWidget')

But you do not want to be over writing your existing styles using this method. This should be used in a 'lost' case scenario. Just demonstrates the power of jQuery

How to override !important?

Overriding the !important modifier

  1. Simply add another CSS rule with !important, and give the selector a higher specificity (adding an additional tag, id or class to the selector)
  2. add a CSS rule with the same selector at a later point than the existing one (in a tie, the last one defined wins).

Some examples with a higher specificity (first is highest/overrides, third is lowest):

table td    {height: 50px !important;}
.myTable td {height: 50px !important;}
#myTable td {height: 50px !important;}

Or add the same selector after the existing one:

td {height: 50px !important;}

Disclaimer:

It's almost never a good idea to use !important. This is bad engineering by the creators of the WordPress template. In viral fashion, it forces users of the template to add their own !important modifiers to override it, and it limits the options for overriding it via JavaScript.

But, it's useful to know how to override it, if you sometimes have to.



Related Topics



Leave a reply



Submit