How to apply !important using .css()? - javascript

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)

Related

how to update style properties in <style> tag using javascript [duplicate]

Is it possible to make changes to a CSS rule-set dynamically (i.e. some JS which would change a CSS rule-set when the user clicks a widget)
This particular CSS rule-set is applied to lots of elements (via a class selector) on the page and I want to modify it when the user clicks the widget, so that all the elements having the class change.
You can, but it's rather cumbersome. The best reference on how to do it is the following article: Totally Pwn CSS with Javascript (web archive link).
I managed to get it to work with Firefox and IE - I couldn't in Chrome, though it appears that it supports the DOM methods.ricosrealm reports that it works in Chrome, too.
This is a modern version based on Totally Pwn CSS with Javascript. It's ES6 I hope don't mind.
function getCSSRule(ruleName) {
ruleName = ruleName.toLowerCase();
var result = null;
var find = Array.prototype.find;
find.call(document.styleSheets, styleSheet => {
result = find.call(styleSheet.cssRules, cssRule => {
return cssRule instanceof CSSStyleRule
&& cssRule.selectorText.toLowerCase() == ruleName;
});
return result != null;
});
return result;
}
This function returns a CSSStyleRule that you can use like this:
var header = getCSSRule('#header');
header.style.backgroundColor = 'red';
Also document.styleSheets list references of the CSSStylesSheets Objects. Other way to acces a specific sytleSheet in the page is by assigning an id to the style or link element in the html code, and get it in javascript using document.getElementById('my-style').sheet. This are some useful methods:
Major Browsers and IE9+ : insertRule(), deleteRule(), removeProperty().
Major Browsers, Firefox? and IE9+ : setProperty().
<stye id="my-style" ...
....
var myStyle = document.getElementById('my-style').sheet
myStyle.insertRule('#header { background: red; }', 0);
It is also possible to dynamically create a new style element to store dynamic created styles, I think should be way to avoid conflicts.
You can edit CLASS in document styleshets as follows
[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.box')
.style.background= 'red';
function edit() {
[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.box')
.style.background= 'red';
}
.box {
margin: 10px;
padding: 10px;
background: yellow;
}
<button onclick="edit()" >Click me</button>
<div class="box" >My box 1</div>
<div class="box" >My box 2</div>
<div class="box" >My box 3</div>
I tried the code via link from #alex-gyoshev comment, but it dosn't work
it fails on the CSS rules with Google fonts in Chrome
it fails on FireFox security checks
So I changed it slightly, but deleted delete functionality since it wasn't needed for me. Checked in IE 11, FireFox 32, Chrome 37 and Opera 26.
function getCSSRule(ruleName) { // Return requested style object
ruleName = ruleName.toLowerCase(); // Convert test string to lower case.
var styleSheet;
var i, ii;
var cssRule = false; // Initialize cssRule.
var cssRules;
if (document.styleSheets) { // If browser can play with stylesheets
for (i = 0; i < document.styleSheets.length; i++) { // For each stylesheet
styleSheet = document.styleSheets[i];
if (!styleSheet.href) {
if (styleSheet.cssRules) { // Browser uses cssRules?
cssRules = styleSheet.cssRules; // Yes --Mozilla Style
} else { // Browser usses rules?
cssRules = styleSheet.rules; // Yes IE style.
} // End IE check.
if (cssRules) {
for (ii = 0; ii < cssRules.length; ii++) {
cssRule = cssRules[ii];
if (cssRule) { // If we found a rule...
// console.log(cssRule);
if (cssRule.selectorText) {
console.log(cssRule.selectorText);
if (cssRule.selectorText.toLowerCase() == ruleName) { // match ruleName?
return cssRule; // return the style object.
}
}
}
}
}
}
}
}
return false; // we found NOTHING!
}
Depending on what you're trying to achieve, a better solution might be to change/add a class to a containing element (body would do!), and define classes accordingly.
.yourclass { color: black }
#wrapper.foo .yourclass { color: red }
#wrapper.bar .yourclass { color: blue }
then you can just use
document.getElementById('wrapper').className='foo';
(or your chosen js framework's wrapper for the same) to change everything with class yourclass inside whatever your wrapper element is.
The APIs for editing stylesheets with JS are, sadly, not consistent across browsers. The YUI Stylesheet Utility attempts to smooth over these differences so you could just use that. You could also look at the source code to figure out how it works if you don't want to use YUI itself.
give your style tag an id, like <style id="ssID">
if someonelse is making your styles for you
tell THAT person to give the style tag an id -
that way you can access it directly without
scrambling around wondering what its index is
// create a hash table
var cssHash = {};
// loop through and populate the hash table
for (let i in (r = ss0.sheet.rules)) {
// selectorText is the name of the rule - set the value equal to the rule
cssHash[r[i].selectorText] = r[i];
}
now you have a hash table for everything in the style sheet -
note that some values will be undefined, but not for
any of the things you care about
if you have, for instance, a class called #menuItem
and you want to change its color to black, do this
cssHash['#menuItem'].style.color = #000;
that line will set the color of the style of the rule
whose index was looked up in the hash table (cssHash)
by the name '#menuItem'
more importantly, you probably have several different
classes that you want to change all at once
kind of like when you switched majors in college
let's say you have four different classes
and you want to set all of their background colors
to the same value, that some user selected from an input
the color selector tag is <input id="bColor" type="color">
and the class rules you want to change are called
#menuItem .homeAddr span and #vacuum:hover
// create a listener for that color selector
bColor.addEventListener('input', function (e) {
// loop through a split list of the four class names
'#menuItem .homeAddr span #vacuum:hover'.split(' ').forEach(function (obj) {
// use the hash table to look up the index of each name
// and set the background color equal to the color input's value
cssHash[obj].style.backgroundColor = bColor.value;
});
}, false); // false added here for the sake of non-brevity
While setAttribute is nice, there is a standard way of doing this across most browsers:
htmlElement.className = 'someClass';
To do it over many elements, you will need a cross browser solution:
function getElementsByClassName( className, context, tagName ) {
context = context || document;
if ( typeof context.getElementsByClassName === 'function' )
return context.getElementsByClassName( className );
if ( typeof context.getElementsByTagName !== 'function' )
return [];
var elements = typeof tagName === 'string' ? context.getElementsByTagName( tagName ) :
context.getElementsByTagName('*'),
ret = [];
for ( var i = 0, il = elements.length; i < il; i++ )
if ( elements[ i ].className.match( className ) )
ret.push( elements[ i ] );
return ret;
}
var elements = getElementsByClassName('someClass');
for ( var i = 0, il = elements.length; i < il; i++ )
elements[ i ].className = 'newClass';
You may want to replace the line:
if ( elements[ i ].className.match( className ) )
With some Regular Expression, but you will have to escape special characters in that case.
To check all stylesheets for the rule and set it:
Your rule:
.aaa: {
background-color: green
}
[...document.styleSheets].flatMap(s=>[...s.cssRules])
.find(i=>i.selectorText=='.aaa').style.backgroundColor = 'red';
Note that the css styles, when accessed through javascript, do not have dashes in them. In the example above, background-color becomes backgroundColor

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.

Overriding !important style

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

Categories

Resources