Creative Juices Bo. Co.

Satisfy Your Thirst For Something Refreshing!

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.