Imx Fix in my experience
« prev next »

August 5, 2003 4:50 AM

In a recent bit of development work, we discovered the beauty and pain of the setAttribute() method. Specifically, we wanted to dynamically create more form elements for people to fill out without having to go back to the server and add in the HTML. So, we do a createlement() and then add in the various attributes that make up an input box. Here's the basics...
  var input = document.createElement("INPUT");

That makes a new input element, and then sets all of the attributes and their values. The result should be something like this...
  <input type="text" name="myinput" id="myinput">
You can try that code right here...
When you click on "Add an Input" some more complex JavaScript than quoted above will execute, and if you are using Navigator, Safari or Mozilla, you will get a new input with all if its necessary attributes defined and populated. The innerHTML will be alerted so you can verify that. Try it, and then view the page source to see what the code is doing.

Notice that I used the word "should" in the my comments above. I say the 's' word for a couple of reasons. Internet Explorer 6 on Win 2k Pro doesn't set any of the attributes. And Internet Explorer 5.2.3 for Mac OSX does something even worse, it throws a JavaScript error on the attempt to set the type attribute. Scouring the net for answers yielded frustrating results.

One particularly delicious find mentions that the Microsoft Developer site provides code that doesn't execute. When I run the code at that link, I get an error at the attempt to set the type attribute. The MSDN even talks about the method as if it were fully supported, but I'm not so sure about that. The only working example I could find seems to be completely IE/Windows specific and mentions that "his method requires an object participating in persistence".

My conclusion is that the setAttribute method is not fully supported in Internet Explorer. So, we resorted to workarounds, and found one. If you do a createElement("SPAN") and then pump it full of innerHTML and then append that to something, you will get your desired effect. But, that's at the price of using non-DOM code.

If anyone else can shed any more light on this, please do. My knowledge on the subject is anecdotal and derived from experimentation. Other data includes weird comments like the following from O'Reilly...

"The book says that the setAttribute() method in IE4 through 5.5 uses propertynames instead of attributenames. I experienced that the same behaviour holds for IE6.0 for PC."
Again, please let me know if you know anything that hasn't been mentioned here already.