23

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 ?

Ali Nadalizadeh
  • 2,726
  • 3
  • 22
  • 24
  • 4
    Not an answer to your question, but differences like this are the biggest "pro" point for using a framework like JQuery, Prototype, MooTools or Dojo. Porting JS becomes 95-99% unnecessary with those. – Pekka Jan 22 '10 at 17:54
  • 1
    Seems this was broken in IE at some point. You should be able use button.setAttribute('style', '') since this method is only responsible for setting the attributes values. The fact that button.style is an object is just another way of setting that same attribute. It seems to be working in IE11 as of this comment. – b01 Oct 24 '16 at 19:09

6 Answers6

39

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
  • 109,858
  • 19
  • 140
  • 171
  • 1
    "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. – Quentin Jan 22 '10 at 18:00
  • Are there any ways, I can add multiple semicolon separated styles without setting each individual attribute ? – Ali Nadalizadeh Jan 22 '10 at 18:03
  • 3
    `button.style.float = 'right'` will also break. There is no float property because float is a reserved keyword in JavaScript. – Quentin Jan 22 '10 at 18:03
  • Fixed bugs. Thanks for catching them David :-) – slebetman Jan 22 '10 at 18:11
  • `button.style.setAttribute('float','right');` is still going to error. – Quentin Jan 22 '10 at 18:47
  • 1
    No, it isn't. There is no setAttribute method on the style property! – Quentin Jan 22 '10 at 19:54
  • 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`. – Quentin Jan 22 '10 at 19:55
  • It also fails follow the best practice of testing hasOwnProperty inside a for loop. – Quentin Jan 22 '10 at 19:56
  • This worked for me in IE7,8,9 and 10. Not sure what the above nay-sayers are on about – Fandango68 Nov 25 '16 at 01:55
  • I'll comment that IE doesn't like properties with a dash (-) so use array syntax with these properties like: div.style["z-index"] = "100"; – Mike Cheel Jun 12 '17 at 19:12
  • 1
    @MikeCheel: That won't normally work at the time I wrote this answer. Maybe it works now but I doubt it. In javascript the proper name for `z-index` is `zIndex`. For every css attribute that contain `-` there is an equivalent style property in camelCase. So `zIndex`, `backgroundImage`, `fontSize` etc. – slebetman Jun 15 '17 at 11:16
  • 1
    @MikeCheel: That's not all. Notice also that the `style` property does not have a `float` property so you cannot do `style.float = 'right'`. Instead it has `cssFloat`. You need to refer to the w3c spec or MDN docs or MSDN docs for the correct name. – slebetman Jun 15 '17 at 11:19
11

You need to use cssText

 button.style.cssText = 'float: right;';
Alex Z
  • 1,362
  • 15
  • 16
6

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';
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

I noticed that setAttribute works in IE only when the attribute does not already exist. Therefore, use remove attribute and then use set attribute.

Haven't tested this for bugs, but conceptually I think this will work:

NOTE - this was written to exist inside object that had property called 'element'.

//Set Property

this.setProperty = function (a, b) {
var c = this.element.getAttribute("style");
var d;
if (!c) {
    this.element.setAttribute("style", a + ":" + b);
return;
} else {
    d = c.split(";")
}

for (var e = 0; e < d.length; e++) {
    var f = d[e].split(":");
    if (f[0].toLowerCase().replace(/^\s+|\s+$/g, "").indexOf(a.toLowerCase().replace(/^\s+|\s+$/g, "")) == 0) {
       d[e] = a + ":" + b
    }
}

d[d.length] = a + ":" + b;
this.element.setAttribute("style", d.join(";"))
}

//Remove Property
this.removeProperty = function (a) {
var b = this.element.getAttribute("style");
var c;
if (!b) {
    return
} else {
    c = b.split(";")
}

for (var d = 0; d < c.length; d++) {
    var e = c[d].split(":");
    if (e[0].toLowerCase().replace(/^\s+|\s+$/g, "").indexOf(a.toLowerCase().replace(/^\s+|\s+$/g, "")) == 0) {
        c[d] = ""
    }
}

this.element.removeAttribute("style");
this.element.setAttribute("style", c.join(";").replace(";;", ";"))
}
Rui Marques
  • 8,567
  • 3
  • 60
  • 91
2

Another useful way to mutate a style property is using the square brackets to access the property. This is useful for accessing properties which because of their name would give a syntax error if expressed normally. In JavaScript it is perfectly permissible to have properties with numeric values, numeric first letters and symbols and spaces as characters, but then you must use the square bracket way of accessing properties.

node.style.z-index = 50;//Firefox says error, invalid assignment left hand side.

node.style["z-index"] = "50";//Works without error
Andrew S
  • 2,847
  • 3
  • 33
  • 50
0

It does work in IE. Just tried it out.

  1. The method is passed a style name and a value
  2. The method then checks to see if there are any styles If no styles attribute exists, then the method simply sets the style and stops
  3. If a style attribute exists, all the styles in the attribute are split into an array
  4. The array is iterated and all applicable style definitions are updated with the new value
  5. The style attribute is then removed from the element
  6. The style attribute is added back to the element with its values set to the new info gathered from the array