Overriding !important style - javascript

Title pretty much sums it up.
The external style sheet has the following code:
td.EvenRow a {
display: none !important;
}
I have tried using:
element.style.display = "inline";
and
element.style.display = "inline !important";
but neither works. Is it possible to override an !important style using javascript.
This is for a greasemonkey extension, if that makes a difference.

There are a couple of simple one-liners you can use to do this.
Set a "style" attribute on the element:
element.setAttribute('style', 'display:inline !important');
or...
Modify the cssText property of the style object:
element.style.cssText = 'display:inline !important';
Either will do the job.
===
I've written a jQuery plugin called "important" to manipulate !important rules in elements, : http://github.com/premasagar/important
===
Edit:
As shared in the comments, the standard CSSOM interface (the API for JavaScript to interact with CSS) provides the setProperty method:
element.style.setProperty(propertyName, value, priority);
E.g:
document.body.style.setProperty('background-color', 'red', 'important');

element.style has a setProperty method that can take the priority as a third parameter:
element.style.setProperty("display", "inline", "important")
It didn't work in old IEs but it should be fine in current browsers.

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.

Building on #Premasagar's excellent answer; if you don't want to remove all the other inline styles use this
//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.

If you want to update / add single style in DOM Element style attribute you can use this function:
function setCssTextStyle(el, style, value) {
var result = el.style.cssText.match(new RegExp("(?:[;\\s]|^)(" +
style.replace("-", "\\-") + "\\s*:(.*?)(;|$))")),
idx;
if (result) {
idx = result.index + result[0].indexOf(result[1]);
el.style.cssText = el.style.cssText.substring(0, idx) +
style + ": " + value + ";" +
el.style.cssText.substring(idx + result[1].length);
} else {
el.style.cssText += " " + style + ": " + value + ";";
}
}
style.cssText is supported for all major browsers.
Use case example:
var elem = document.getElementById("elementId");
setCssTextStyle(elem, "margin-top", "10px !important");
Here is link to demo

If all you are doing is adding css to the page, then I would suggest you use the Stylish addon, and write a user style instead of a user script, because a user style is more efficient and appropriate.
See this page with information on how to create a user style

https://developer.mozilla.org/en-US/docs/Web/CSS/initial
use initial property in css3
<p style="color:red!important">
this text is red
<em style="color:initial">
this text is in the initial color (e.g. black)
</em>
this is red again
</p>

https://jsfiddle.net/xk6Ut/256/
One option to override CSS class in JavaScript is using an 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)

Rather than injecting style, if you inject a class(for eg: 'show') through java script, it will work. But here you need css like below. the added class css rule should be below your original rule.
td.EvenRow a{
display: none !important;
}
td.EvenRow a.show{
display: block !important;
}

There we have another possibility to remove a property value from the CSS.
Like using the replace method in js. But you have to know exactly the ID of the style, or you can write a for loop to detecting that by (count styles on the page, then check if any of those 'includes' or 'match' an !important value. & you can count also - how much contains them, or just simply write a global [regexp: /str/gi] replacing method)
Mine is very simple, but I attach a jsBin, for example:
https://jsbin.com/geqodeg/edit?html,css,js,output
First I set the body background in CSS for yellow !important, then I overrided by JS for darkPink.

Below is a snippet of code to set the important parameter for the style attribute using jquery.
$.fn.setFixedStyle = function(styles){
var s = $(this).attr("style");
s = "{"+s.replace(/;/g,",").replace(/'|"/g,"");
s = s.substring(0,s.length-1)+"}";
s = s.replace(/,/g,"\",\"").replace(/{/g,"{\"").replace(/}/g,"\"}").replace(/:/g,"\":\"");
var stOb = JSON.parse(s),st;
if(!styles){
$.each(stOb,function(k,v){
stOb[k] +=" !important";
});
}
else{
$.each(styles,function(k,v){
if(v.length>0){
stOb[k] = v+" !important";
}else{
stOb[k] += " !important";
}
});
}
var ns = JSON.stringify(stOb);
$(this).attr("style",ns.replace(/"|{|}/g,"").replace(/,/g,";"));
};
Usage is pretty simple.Just pass an object containing all the attributes you want to set as important.
$("#i1").setFixedStyle({"width":"50px","height":""});
There are two additional options.
1.To just add important parameter to already present style attribute pass empty string.
2.To add important param for all attributes present dont pass anything. It will set all attributes as important.
Here is it live in action. http://codepen.io/agaase/pen/nkvjr

Related

Break CSS into rules

I have the content of a CSS file as a string I got with an AJAX request.
I need to break it into rules that I can feed into styleSheet.insertRule
What is the best way to achieve this correctly and efficiently ? I do not want to include/write a full CSS parser just for that if possible ...
I considered simply splitting on '}' but this will not work if there are #media clauses which created nested curly brackets, and I am not sure it is correct otherwise ...
Thanks!
You can simply create a new <style> element using the stylesheet text you have and insert it into the <head> element.
var style = `
div {
color: blue;
}`;
setTimeout(function() {
var elem = document.createElement("style");
elem.innerHTML = style;
document.head.appendChild(elem);
}, 1000);
<div>
Some text
</div>
The solution from Nisarg Shah probably does the job, but here's an alternative. It uses the css.js library to parse the CSS string into a JS array, which can then be inserted using stylesheet.insertRule().
The two advantages this method has:
It breaks the CSS into rules as stated in the question
It would allow styles to be filtered or altered before insertion
Also, this is a simplified solution that will not work with more complicated CSS containing media queries or similar rules. For a more robust solution, the function would need to handle those types of style rules, and more info on how to do that can be found in the MDN docs.
Here's the approach:
Get the CSS from your API
Parse the CSS into a JS array of objects
Loop through the CSS rules and create the CSS style string
Add the style string to the stylesheet with insertRule()
var cssString = `
div {
color: green;
font-size: 24px;
}`;
setTimeout(function() {
var parsedStyles = addStylesAndReturnParsedStyles(cssString);
console.log(parsedStyles)
}, 1000);
var addStylesAndReturnParsedStyles = function(cssString) {
var parser = new cssjs();
var parsed = parser.parseCSS(cssString);
var styleEl = document.createElement('style'),
styleSheet;
// Append style element to head
document.head.appendChild(styleEl);
// Grab style sheet
styleSheet = styleEl.sheet;
parsed.forEach(style => {
var selector = style.selector;
var rules = style.rules;
var propStr = '';
for (var i = 0; i < rules.length; i++) {
var prop = rules[i];
propStr += prop.directive + ':' + prop.value + ';\n';
}
// Insert CSS Rules
styleSheet.insertRule(selector + '{' + propStr + '}', styleSheet.cssRules.length);
});
return parsed;
};
<script src="https://cdn.rawgit.com/jotform/css.js/master/css.min.js"></script>
<div>Here's some content</div>

How can I add the !important tag to the css produced by this javascript? [duplicate]

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.
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 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.
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');
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.
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.
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.
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.
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.
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");
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.
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');
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);
}
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;}
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;
}
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>
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.
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); }
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.
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 = '';
I think it works OK and can overwrite any other CSS before (this: DOM element):
this.setAttribute('style', 'padding:2px !important');
Do it like this:
$("#elem").get(0).style.width= "100px!important";
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
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/
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;}
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.
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;'
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! :)
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.
The safest workaround to this is to add a class and then do the magic in CSS :-), addClass() and removeClass() should do the work.
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)

Dynamically loaded CSS property want appear [duplicate]

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.
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 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.
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');
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.
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.
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.
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.
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.
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");
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.
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');
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);
}
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;}
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;
}
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>
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.
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); }
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.
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 = '';
I think it works OK and can overwrite any other CSS before (this: DOM element):
this.setAttribute('style', 'padding:2px !important');
Do it like this:
$("#elem").get(0).style.width= "100px!important";
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
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/
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;}
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.
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;'
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! :)
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.
The safest workaround to this is to add a class and then do the magic in CSS :-), addClass() and removeClass() should do the work.
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)

How to return a javascript set style property to CSS default

I'm trying to work out how, after changing style properties with javascript, I can revert to the value in the stylesheet (including the units).
In the example below, I'd like the output to read 100px (the value in the CSS), rather than 10px, as getComputedStyle gives.
I'd also keep the dummy div at top:25px, so removing the style property won't work.
The best I have is cloning the node and reading the height and storing in a property (http://jsfiddle.net/daneastwell/zHMvh/4/), but this is not really getting the browser's default css value (especially if this is set in ems).
http://jsfiddle.net/daneastwell/zHMvh/1/
<style>
#elem-container{
position: absolute;
left: 100px;
top: 200px;
height: 100px;
}
</style>
<div id="elem-container">dummy</div>
<div id="output"></div>
<script>
function getTheStyle(){
var elem = document.getElementById("elem-container");
elem.style.left = "10px";
elem.style.top = "25px";
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("left");
document.getElementById("output").innerHTML = theCSSprop;
}
getTheStyle();
</script>
Just clear the inline style you wish to fallback to original stylesheet on.
elem.style.left = null;
The style object has a built-in removeProperty() method, so you could do something like:
elem.style.removeProperty('left');
As far as I know, this will have exactly the same effect as setting the property to null, as abaelter suggested. I just thought it might be worth including for the sake of completeness.
Combining abaelter's answer and http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/ gives us the below function:
var getCssStyle = function(elementId, cssProperty) {
var elem = document.getElementById(elementId);
var inlineCssValue = elem.style[cssProperty];
// If the inline style exists remove it, so we have access to the original CSS
if (inlineCssValue !== "") {
elem.style[cssProperty] = null;
}
var cssValue = "";
// For most browsers
if (document.defaultView && document.defaultView.getComputedStyle) {
cssValue = document.defaultView.getComputedStyle(elem, "").getPropertyValue(cssProperty);
}
// For IE except 5
else if (elem.currentStyle){
cssProperty = cssProperty.replace(/\-(\w)/g, function (strMatch, p1) {
return p1.toUpperCase();
});
cssValue = elem.currentStyle[cssProperty];
}
// Put the inline style back if it had one originally
if (inlineCssValue !== "") {
elem.style[cssProperty] = inlineCssValue;
}
return cssValue;
}
Placing in your example code and testing:
console.log("getCssStyle: " + getCssStyle("elem-container", "left"));
Gives us getCssStyle: 100px allowing you to see the original CSS value. If you just want to revert the value then do as abaelter says and null the CSS value you want to revert.

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.
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 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.
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');
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.
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.
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.
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.
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.
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");
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.
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');
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);
}
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;}
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;
}
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>
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.
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); }
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.
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 = '';
I think it works OK and can overwrite any other CSS before (this: DOM element):
this.setAttribute('style', 'padding:2px !important');
Do it like this:
$("#elem").get(0).style.width= "100px!important";
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
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/
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;}
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.
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;'
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! :)
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.
The safest workaround to this is to add a class and then do the magic in CSS :-), addClass() and removeClass() should do the work.
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)

Categories

Resources