Simon Proctor (scimon) wrote,

Interesting IE bug.

I've found an interesting little bug in Internet Explorer, by interesting I of course mean totally bloody annoying. I shall walk you through the situation. You have an existing input element you'd like to make a copy of with a new name. EG:

<input id="target" name="target_input" value="value">

So you grab it, clone it, rename the clone and append it like so:

var base = document.getElementById( 'target' );
var newNode = base.cloneNode( true );
newNode.name = 'new_input';
newNode.id= 'new_target';
base.parentNode.appendChild( newNode );

Woot! You now have two input tags. Here's where it gets interesting. what would you expect the following code to do?

var list = document.getElementsByName( 'target_input' );
for ( var i = 0; i < list.length; i++ )
{
   list[i].value = list[i].name;
}

If you answer was set the first input field to have a value of 'target_input' and the second would keep it's value of 'value' then well done, have a banana. If your answer was set the first input field to have a value of 'target_value' and the second would keep it's value of 'new_input' then I guess you work for Microsoft.

Yup. document.getElementsByName( 'target_input' ); returns our new element in IE despite it knowing that the name has been changed. Interestingly document.getElementsByName( 'new_input' ); returns a single element list with just our new element in it. Yup, IE seems to have gone a tad nutty. The moral of this story seems to be avoid cloneNode with form elements and IE. Joy.

Tags: ie bugs, javascript
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic
  • 9 comments