Tutorial :setAttribute style not working in IE


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 !


Try changing that to

var box = document.getElementById('box');  box.style.width = '200px';  box.style.backgroundColor = 'red';  


The ultimate answer is cssText:

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

The side note is

Avoid set/getAttribute everywhere you can!


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.


you can use setAttribute that is also compatible with IE-8 and IE-7

var el = document.getElementById('id' + id);  el.setAttribute('fontWeight','bold');  el.setAttribute('color','red');  el.setAttribute('fontSize','150%');  el.setAttribute('bgColor','red');  

for assigning a class to an element, i suggest following

el.className = "class-name";  


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

$('box').setStyle({    width: '200px',    backgroundColor : 'red'  });  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »