Site Navigation

Wednesday, October 24, 2007

bug 235 - createElement is broken in IE

Issue: #235
Affects: IE6, IE7

According to the DOM specs for ECMAScript, adding an input field should be as easy as the code snippet below.

Example:

<script type="text/javascript">
var myNewField = document.createElement('input');
myNewField.setAttribute('name', 'tags');
//set any other attributes...
//add to the DOM
document.getElementsByTagName('form')[0].appendChild( myNewField );
</script>


However, if you try this in IE, it will "appear" to work, until you submit the page, or attempt to query the field by name.

IE (for reasons unknown) did not set the name attribute. (seriously, try it!)

The solution is exposed in this MSDN article, whereby IE allows a (horribly) invalid parameter to the createElement() method to get around this bug.


Known Workarounds: One.

You will need to determine if the current browser is IE, then, execute the applicable createElement call.

Example Workaround Code:

<script type="text/javascript">
//use browser sniffing to determine if IE or Opera (ugly, but required)
var isOpera, isIE = false;
if(typeof(window.opera) != 'undefined'){isOpera = true;}
if(!isOpera && navigator.userAgent.indexOf('Internet Explorer')){isIE = true);

var myNewField = null;
if(!isIE){
myNewField = document.createElement('input');
myNewField.setAttribute('name', 'tags');
} else {
myNewField = document.createElement('<input name="tags"/>');
}
//set any other attributes...
//add to the DOM
document.getElementsByTagName('form')[0].appendChild( myNewField );
</script>




Related Issues: bug 242, bug 237.