Aakash Chakravarthy
Aakash Chakravarthy

Reputation: 10691

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 !

Upvotes: 3

Views: 9458

Answers (5)

Asif hhh
Asif hhh

Reputation: 1552

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";

Upvotes: 0

gblazex
gblazex

Reputation: 50109

The ultimate answer is cssText:

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

The side note is

Avoid set/getAttribute everywhere you can!

Upvotes: 12

Javaguru
Javaguru

Reputation: 910

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

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

Upvotes: -1

Pointy
Pointy

Reputation: 413702

Try changing that to

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

Upvotes: 5

Quentin
Quentin

Reputation: 943207

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.

Upvotes: 3

Related Questions