views:

501

answers:

2

I'm porting a piece of JS code written for Firefox into Internet Explorer. I faced a problem of changing style of an element using setAttribute method which was working on Firefox.

button.setAttribute('style', 'float: right;');

I tried setting the style member of button and it didn't work either. This was the solution in case of setting onclick event handler.

button.style = 'float: right;';

First I wanna know the solution for the above problem and
Second are there any maintained lists for these differences between browsers ?

+4  A: 

Because style itself is an object. What you want is:

button.style.setAttribute('cssFloat','right');

But IE doesn't support setAttribute for style objects. So use the fully cross-browser supported:

button.style.cssFloat = 'right';

As for reference, I always go to www.quirksmode.org . Specifically: http://www.quirksmode.org/compatibility.html . Click on all the DOM related stuff.

And finally, to set multiple attributes I usually use something like:

function setStyle(el,spec) {
    for (var n in spec) {
        el.style[n] = spec[n];
    }
}

usage:

setStyle(button,{
    cssFloat : 'right',
    border : '2px solid black'
});

Note: object.attribute = 'value' although works in all browsers may not always work for non-HTML DOM objects. For example, if your document contains embedded SVG graphics that you need to manipulate with javascript you need to use setAttribute to do it.

slebetman
"Because style itself is an object" is only half the story and "button.style.setAttribute" will throw an error because the style object doesn't have a setAttribute method.
David Dorward
Are there any ways, I can add multiple semicolon separated styles without setting each individual attribute ?
Ali Nadalizadeh
`button.style.float = 'right'` will also break. There is no float property because float is a reserved keyword in JavaScript.
David Dorward
Fixed bugs. Thanks for catching them David :-)
slebetman
`button.style.setAttribute('float','right');` is still going to error.
David Dorward
@David: Thanks for spotting that. Fixed.
slebetman
No, it isn't. There is no setAttribute method on the style property!
David Dorward
And your multiple setting script is broken too! `foo.n` references the property `n` not the property with the same name as the value of the variable `n`.
David Dorward
It also fails follow the best practice of testing hasOwnProperty inside a for loop.
David Dorward
David Dorward is correct. Listen to him.
Tim Down
+2  A: 

getAttribute and setAttribute are broken in Internet Explorer.

The correct syntax for what you are trying to achieve is:

button.style.cssFloat = 'right';

The correct solution to the problem is more likely to be:

button.className = 'a class that matches a pre-written CSS rule-set';
David Dorward