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

≯℡__Kan透↙ 提交于 2019-12-10 20:42:37

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/1361446/ie8-the-option-tag-gets-a-selected-attribute-by-default-and-clonenode-makes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!