Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setAttribute is not working for 'style' attribute on IE

Tags:

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 ?

like image 651
Ali Nadalizadeh Avatar asked Jan 22 '10 17:01

Ali Nadalizadeh


People also ask

Why is setAttribute not working?

The "setAttribute is not a function" error occurs for multiple reasons: calling the setAttribute() method on a value that is not a DOM element. placing the JS script tag above the code that declares the DOM elements. calling the setAttribute method on a jQuery object (should use attr() instead).

How do I add setAttribute?

Element.setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value. To get the current value of an attribute, use getAttribute() ; to remove an attribute, call removeAttribute() .


2 Answers

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.

like image 123
slebetman Avatar answered Sep 22 '22 12:09

slebetman


You need to use cssText

 button.style.cssText = 'float: right;'; 
like image 29
Alex Z Avatar answered Sep 24 '22 12:09

Alex Z