I have recently needed to write code that uses JavaScript to add
elements dynamically to a web page on the client. I read the relevant
W3C documents and wrote the code, and it seemed to work fine. Until I
tried it on Internet Explorer. After some digging, I found an
explanation in the MSDN
DHTML reference
, on the page describing the NAME

The NAME attribute cannot be set at run time on elements
dynamically created with the createElement method. To create an element
with a name attribute, include the attribute and value when using the
createElement method.

The trouble is that including attributes in calls to createElement
is a Microsoft-only extension. If you try to do this (e.g. document.createElement("<inputname='brian'>")), there are at least three possible outcomes:

  • The browser throws an exception because “<input name=’brian’>”
    is not a valid element type. This is the correct behaviour.
  • The browser creates an element with type = “input” and name =
    “brian”. This is what IE 6 does.
  • The browser creates an element with the invalid type = “<input
    name=’brian’>”. This is what Netscape 7.1 and Opera 8.5 do. Thanks to
    for pointing this out.

So if you want to create named elements dynamically, you have to be a
bit crafty. It’s no good trying the correct approach first, because
this will fail on IE6 with no way for your code to check. Therefore, I
first attempt to create the element by including the name attribute in
the call to createElement, and check the result. If it checks out OK,
then I’m probably running on IE6 and all is well. Otherwise, I just try
again using the correct method of creating the element and then setting
the name.

Here’s the function I came up with that allows you to create named
elements on any browser. Pass it the name and type of the element you
want to create. I have tested this on various Windows browsers: IE5, 5.5
and 6; Firefox 1 and 1.5; Mozilla 1.7; Netscape 7.1 and 8; and Opera
7.23 and 8.5. Please let me know if you notice problems on these or any
other browser.

This code doesn’t use browser-sniffing techniques. Instead it simply
tries to create the element using the Internet Explorer method first; if
this fails it uses the standard method.

Note also that there are problems setting the name attribute even on
static elements:

Microsoft JScript allows the name to be changed at run
time. This does not cause the name in the programming model to change in
the collection of elements, but it does change the name used for
submitting elements.

Be sure to test thoroughly — don’t just assume it will work (as I

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注