IE6 can't add options then select them after accessing childNodes

IE 6 can throw an error "Error: Could not set the selected property. Unspecified error." when you try to manipulate select elements by adding options and then selecting one of your newly created items. I came across this while trying to use jQuery's .val() function to set the selected element after I had added some options to my select.

Here's what's running on this page.:

      window.onload = function() {        
        var select = document.getElementById('mySelect');
        
        var option = document.createElement('option');
        
        option.value = 'CA';
        option.innerHTML = 'CA';
        
        select.appendChild(option);
        
        // Just asking about the children kills it!
        select.childNodes;
        
        option.selected = true;
     };
     

This is the simplest repro I could make. Note that the error will only occur if you call appendChild, then ask for the select's childNodes, then set the selected property on the newly created option. If you set selected earlier, either before appendChild or after it, there's no problem. And if you omit childNodes, it works. The problem with jQuery is that its .val() function loops over childNodes looking for an option to set, and thus always triggers the bug.

If you wrap the code that sets selected in a setTimeout it works, surprisingly enough. I have to assume it needs to give control back to the browser to let state settle.

Another way to get this to work is to wrap the code that sets selected in a try/catch block and just swallow the error from IE. It seems to set the element as selected properly despite the error!

Yet another way to work around this appears to be to use setAttribute instead of setting the property directly. option.setAttribute('selected', true) causes no error.

A sub-bug is that setting selectedIndex on the select element won't work to select the new option whether or not you've accessed childNodes. It doesn't cause an error, it just doesn't do anything. For example, I can set the selectedIndex to 1, which selects "PA", but not to 2, which would select my new option. I might break that out into a separate bug later.

This has been fixed in IE7.

Back to Browser Bugs