简体   繁体   中英

IE8: The option tag gets a “selected” attribute by default (And cloneNode makes a mess of it)

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 :-\\

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM