Overriding !important style

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...

2) Modify the cssText property of the style object:

element.style.cssText = 'display:inline !important';

Either will do the job.

===

BTW - if you want a useful tool to manipulate !important rules in elements, I've written a jQuery plugin called "important": http://github.com/premasagar/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.

Tags:

Javascript

Css