IE can’t set name attribute dynamically.
May 1, 2008, 12:00 pm
Filed under: firefox, ie, javascript, Uncategorized

I keep tripping myself up with this one, IE is unable to set the name attribute for any dynamically created DOM nodes. It doesn’t matter if you clone an existing node, or create a new one, IE won’t set the name attribute.

Have a look at this example:

var newCheckbox = document.createElement('input');
newCheckbox.setAttribute('type', 'checkbox');
newCheckbox.setAttribute('name', x[i].name);
newCheckbox.setAttribute('value', '0');
newCheckbox.setAttribute('checked', 'checked');


Will result in a new input element with no name attribute. The only way I’ve found to counter this, that works in both IE & Firefox is to use innerHTML.

var newCheckbox = document.createElement("span");
newCheckbox.innerHTML ="[input name='" + x[i].name + "' type='checkbox' value='0' checked='checked']";

Is there a better way? I’d be interested to hear about any other solutions that might work.



3 Comments so far
Leave a comment

On this site:
There is a workaround provided (for IE). I would advise it over what you are doing because your example is adding an extra level to the DOM that isn’t needed (and depending on your situation) might break your CSS nesting rules.

I’ve often seen this abreviated into one function that takes the Element name to create, AND the value for the name attribute (if applicable).

If it is IE and the name value is passed, it will then apply the hack to fix IE.


Comment by Martin

Hi Martin,

I prefer not to use browser detection like that, mainly for the reasons as explained at Quirksmode, at least this way I know it’s going to work.

Comment by Stuart Grimshaw

Actually there isn’t a good workaround for IE if you’re creating an element from another element (i.e. cloneNode). As far as I can tell, to overwrite the old name you’ll need to innerHTML the parent node, and then do a search and replace on the old name attribute. This is annoying, because at least in my case, the clone will be under the same parent as the original…

Comment by Ryan

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: