I am having trouble applying a style that is !important
. I’ve tried:
$(\"#elem\").css(\"width\", \"100px
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); }
May be it look's like this:
var node = $('.selector')[0]; OR var node = document.querySelector('.selector');
node.style.setProperty('width', '100px', 'important');
node.style.removeProperty('width'); OR node.style.width = '';
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.
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;}
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;'
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);
}