Javascript and DOM craziness

OK, guess what this (simplistic) HTML file should display when opened in your favorite browser?

<html>
<head>
<script type="text/javascript">
window.onload = function () {
  var dropDown = document.getElementById('select');
  var newOption = document.createElement('option');
  newOption.innerHTML = 'four';
  dropDown.appendChild(newOption);
  dropDown.options.selectedIndex = dropDown.options.length - 1;
}
</script>  
</head>
<body>
  <select id="select">
    <option>one</option>
    <option selected="true">two</option>
    <option>three</option>
  </select>
</body>
</html>

Firefox/Safari/Opera all show a drop down list on the page, with the option ‘four’ selected. Internet Explorer (version 6.something, haven’t tested it with 7) shows it with the option ‘two’ selected.

It seems that manipulating the DOM with Javascript is more tricky than I thought. Replacing the Javascript with this works:

window.onload = function () {
  var dropDown = document.getElementById('select');
  var newOption = document.createElement('option');
  newOption.innerHTML = 'four';
  dropDown.appendChild(newOption);
  window.setTimeout(function () {
      dropDown.options.selectedIndex = dropDown.options.length - 1;
    }, 100);
}

How very weird… This error came up at work today, and I spent a couple of minutes really puzzled trying to figure out what I did wrong. Thankfully, I trust IE even less than I trust my code; and thought there must be some concurrency issue (or is it some premature optimization issue) going on with the DOM, and tried the setTimeout hack.

I loves me some lexical scoping.