Archive for the ‘Firefox’ Category

How to overwrite an !important style property from JavaScript

20/11/2009 2 comments

So today I had to change the background color of a div, which had a CSS class on it, which specified something like:

.cell-selected {background-color : #dedede !important}

Obviously, the first thing I tried in JavaScript was pretty straight-forward, but also wrong: = '#fafafa !important'

This doesn’t work neither on Firefox (3.5), nor on IE (7, 8).
Searching the internet, I found out that the style object has a setProperty method, which has 3 parameters:

setProperty(property, value, priority)

where priority is either an empty string, or ‘important’. However, as with most solutions easy to find, it only works on Firefox, Safari, Opera, probably Chrome too. The apparent solution on Internet Explorer was to create a style tag and add some text content to it, creating a new css class, with the new background color set as !important, then applying that class to htmlelement. All the info regarding this problem can be found on this thread here. The bad news is:

var   styleElement = document.getElementById('styles_js');
    if (!styleElement) {
        styleElement = document.createElement('style');
        styleElement.type = 'text/css'; = 'styles_js';

doing something like this won’t help at all. In fact, the call to appendChild will raise an error. To clear this up I started yet again a search on-line. The result is this page. Unfortunatelly, not one solution worked for me. They either raised errors, or, when I did the styleElement.text assignment, it worked on IE8, but not on IE7.

Anyway, after renewed efforts, I found this link right here, which explains very well how to handle style tag creation in IE. However, simply creating DOM nodes and leaving them be is not a good solution. So if you do this, make sure you remove them from the DOM after you’ve done your job. The alternative is creating a memory leak (not a big one, but if the programming style isn’t defensive enough, the page could start leaking memory like a sieve).

So, the final solutions was actually something like:

    var newStyle = document.createStyleSheet();
    newStyle.addRule('colorstyle', 'background-color : #fafafa !important;');'colorstyle');
}else{'background-color', '#fafafa', 'important');
Categories: CSS, Firefox, IE bugs