views:

65

answers:

4

Hello,

Setting the style attribute to elements is not working in IE 6/7 . But in other browsers, it works well.

The code i am using is

var box_style = 'width: 200px; background:red';

document.getElementById('box').setAttribute("style", box_style);

This works in all other browsers except IE 6/7

Am i doing anything wrong ? or is there any solution for this problem ? Please help !

+3  A: 

Internet Explorer 6-7 has a broken implementation of setAttribute / getAttribute. Don't use them.

Essentially, setAttribute (for IE) looks something like this:

function (attribute, value) {
    this[attribute] = value;
}

So if there isn't a 1:1 relationship between the property name and the attribute name, it breaks.

Set your properties individually, or, and this is generally better, set className and define the styles in an external stylesheet.

David Dorward
+1. Unless each element really is being styled uniquely, `className`+stylesheet is usually a much cleaner approach.
bobince
+2  A: 

Try changing that to

var box = document.getElementById('box');
box.style.width = '200px';
box.style.backgroundColor = 'red';
Pointy
how to set `-webkit-border-radius` and other css3 properties ?
Aakash Chakravarthy
General rule: Drop the hyphens and capitalize the following letter: `background-color` becomes `backgroundColor`, `-webkit-border-radius` becomes `WebkitBorderRadius`.
RoToRa
actually `-webkit` is an exception here. It should be `WebkitBorderRadius`, like it is `MozBorderRadius`, but actually it's `webkitBorderRadius`.
bobince
@bobince Seriously? Sometimes I think Apple is worse than Microsoft. Thanks for the info.
RoToRa
To be fair, there's no standard that *requires* style names to translate to properties by replacing `-x` with `X`, that's just what's always been done. Whilst Mozilla's initial capitalisation is the most logical by this unwritten rule, you can also see why WebKit would prefer not to have a property name beginning with a capital letter (InitialCap identifiers being normally reserved for classnames).
bobince
A: 

Alternatively you could use PrototypeJS framework (http://www.prototypejs.org), which allows you to do the following:

$('box').setStyle({
  width: '200px',
  backgroundColor : 'red'
});
Javaguru
In what way is that superior to `box.style.width= ...;`?
bobince
Well, it's an alternative, not really superior. But in order to overcome some cross-browser-problems, using a framework like PrototypeJS, jQuery, MooTools, .. is usually a good idea.
Javaguru
+1  A: 

The ultimate answer is cssText:

el.style.cssText = 'width: 200px; background:red';

The side note is

Avoid set/getAttribute everywhere you can!

galambalazs