IE6 and IE7 does not like you using setAttribute on style

setAttribute("style","YOUR STYLE INFO")

I'm right in the middle of a couple of large projects right now, hence the lack of posts lately, but I wanted to share a little problem I just ran into with everyone.

I like to keep my JavaScript condensed, so I like to use setAttribute for style information. But one of my clients reported a problem with a simple survey window I created recently. Apparently, Internet Explorer (go figure) wasn't playing nice with the script I created.

I tracked the problem down to using "setAttribute" to set an objects style. Here's an example of what I had:

var box = document.createElement("div");
box.setAttribute("id", "mySurveyBox");
box.setAttribute("style","margin: 0; padding: 0");
mainBox.appendChild("box");

For whatever reason, it worked in Safari and FireFox, but IE was not displaying the style information. Everything else I used setAttribute on seemed to set properly. Like the objects "ID" attribute.

The fix for this was simple. I just needed to set the style information directly instead of using the setAttribute method. Here's what the new code looked like after the fix:

var box = document.createElement("div");
box.setAttribute("id", "mySurveyBox");
box.style.margin = "0";
box.style.padding = "0";
mainBox.appendChild("box");

Not sure why IE has problems with this, but I thought I would share, in case anyone else ran into the same problem. If anyone has any insight into this problem, I would love to hear about it.

3 responses to "IE6 and IE7 does not like you using setAttribute on style"

Eric Verlet
Hello,

I was running into the same problem as the one described in this article and i discovered a technique that allows to specify the style attribute as you want.

Here is my code :

document.getElementById('yourId').style.cssText="border:0px solid black;";

You can specify any css between the two quotes. It work for IE 6 and IE 7
Jamal Ali
Thank you so much guys!!

I had been pulling my hair for a week!!
tee
tee says:
Thanks for the tip, works great!

Have something to say? Leave a comment!

You don't have to be registered to leave a comment. Unregistered user's comments will be approved before going live.




You are currently posting as an unregistered user.
This means that your comment will be reviewed prior to going live. If you are a registered user, please . New user? No problem, register for an account, it's FREE! Benefits include, posting instantly, screen name protection, collaboration recognition, subscribe to article updates, and so much more!