228

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.

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Enrico
  • 10,377
  • 8
  • 44
  • 55

11 Answers11

427

There are a couple of simple one-liners you can use to do this.

  1. Set a "style" attribute on the element:
element.setAttribute('style', 'display:inline !important');

or...

  1. 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');
S-Flavius
  • 292
  • 2
  • 14
Prem
  • 15,911
  • 11
  • 31
  • 35
  • I think that using cssText is simpler then adding a `style` tag. – Guss Dec 14 '10 at 14:29
  • 1
    @Guss - The first example I gave is for a `style` attribute, not a tag/element. – Prem Dec 17 '10 at 23:56
  • Yes, I know- I compared your answer to @J-P's selected one, and I tried to say that I think your's is better. – Guss Dec 19 '10 at 15:16
  • 77
    To prevent overriding other properties, you man want to use `element.style.cssText += ';display:inline !important;';` – user123444555621 Feb 02 '11 at 12:03
  • See also the CSSOM standard, [style.setProperty(property, value, priority)](http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setpropertyproperty-value-priority) and [style.setPropertyPriority(property, priority)](http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setpropertypriorityproperty-priority) and [this answer](https://stackoverflow.com/a/8894528/165716). – Prem Jun 03 '15 at 16:00
  • 4
    @user123444555621, Premasagar. Might as well use the better option: `element.style.setProperty`. – Pacerier Apr 14 '17 at 05:51
  • I'm trying to set a variable value as the property value, but I cannot use this syntax: `html.style.cssText = "background-color: \`${bgColor}\` !important;";` or `html.setAttribute("style","background-color: \`${bgColor}\` !important;");` neither. How can I do that? – Vahid Nov 08 '22 at 09:37
297

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.

sth
  • 222,467
  • 53
  • 283
  • 367
  • 3
    Works in IE 9 https://msdn.microsoft.com/en-us/library/ie/ff975226%28v=vs.85%29.aspx – Samuel Katz Apr 10 '15 at 16:13
  • 8
    Best solution, since it does not override the whole style attribute and is the way W3C meant it to work. – stfn May 09 '16 at 20:25
  • its downside is I can't use property names in camelCase like `boxShadow` – Pavan Jul 12 '18 at 12:35
  • @Pavan It's easy to just use the hyphenated form instead, or if you need to automatically convert it just write a function. – alexia Dec 29 '18 at 13:46
50

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.

James
  • 109,676
  • 31
  • 162
  • 175
  • 10
    This could be replaced by a one-liner. See below: http://stackoverflow.com/questions/462537/overriding-important-style-using-javascript/1577204#1577204 – Prem Oct 23 '09 at 11:20
  • 2
    How are you gonna find the selector that actually triggers the style? I think this requires parsing all stylesheets, which is a pretty tough job. – user123444555621 Feb 02 '11 at 12:03
  • the bad is sometimes it cannot override '!important', the better is set directly in element. – uingtea Jan 21 '22 at 03:47
4

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.

Hashbrown
  • 12,091
  • 8
  • 72
  • 95
1

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

  • What extra information or improvement does this answer provide ? – Pogrindis Dec 21 '16 at 14:31
  • This function is short, simple and easy to understand. You can add important option. It doesn't removing all element styles. It overwriting or adding single style in element styles attibute. You don't need any JS frameworks. And the most important thing is that this function is working in every browser. – Marek Skrzyniarz Dec 21 '16 at 16:24
0

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

erikvold
  • 15,988
  • 11
  • 54
  • 98
0

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>
zloctb
  • 10,592
  • 8
  • 70
  • 89
  • Initial doesn't reset important. You're not setting the p's color but the em's color. Indeed, change color:initial to color:green and it would work too. – Pacerier Apr 14 '17 at 07:11
0

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)
Razan Paul
  • 13,618
  • 3
  • 69
  • 61
0

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;
}
Pons Purushothaman
  • 2,225
  • 1
  • 14
  • 23
0

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.

matthias_h
  • 11,356
  • 9
  • 22
  • 40
-1

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

agaase
  • 1,562
  • 1
  • 15
  • 24