views:

506

answers:

3

IE seems to add automatically a "selected" attribute on the option tag.
But then if you cloneNode it, things get weird.

If you open a page in IE8 with the code below:

<html>
<body>
  <form><select><option>o1</option></select></form>
  <script>

      // without clone node
      var elm = document.getElementsByTagName('form')[0];
      alert(elm.innerHTML);

      // using the form as the root to clone
      elm = document.getElementsByTagName('form')[0].cloneNode(true);
      alert(elm.innerHTML);

      // using the select as the root to clone
      elm = document.getElementsByTagName('select')[0].cloneNode(true)
      alert(elm.innerHTML);

  </script>
</body>
</html>

You will get:

A 1st alert, with a miserable "selected" attribute on the option tag
A 2nd alert, with no attribute on the option tag ( This is OK, as in any other browser! )
A 3rd alert, with the "selected" appearing again

Any idea why this attribute appears?
And then why cloneNode seems to randomly remove it or not?

Note: You may think why this poor guy has a problem with this?
The reason is I'm a contributor of the JS templating library PURE
And I'm having some hard time to find a clean solution for this problem :-\

A: 

The reason that the selected attribute is added is that it is the first option element within the select element. When this is true and no other option element is already marked as selected, IE will make the first option element selected. When you clone a node as you did without putting it in the dom, it cannot be selected. If you want consistent results, just set the selected attribute manually.

spudly
A: 

Thanks for your reply.
I don't want it selected, that's precisely the problem.
IE seems to select it automatically but then with the cloneNode, the result is inconsistant.

Mic
A: 

Good to know, I don't think its too big a deal though, it doesn't effect functionality just the innerHTML

John-David Dalton