Select Tags in IE: innerHTML
I just wanted to document this rather frustrating bug here, so I can look it up later, and hopefully help anyone else who is running into something similar. This bug involves select
tags, specifically setting their innerHTML
property.
I had a list of options to give to the user, and a select box would work perfectly. Since DOM methods have burned me in the past, I felt innerHTML
was the safer route. It appears, that they both have safety curves like a sine and cosine graph.
The Buggery
Here’s what I thought would work of stupendously!
var options = '<option>' + item.options.join('</option><option>') + '</option>';selectEl.innerHTML = options;
It works in Firefox, Safari, Chrome, etc. Except Internet Explorer. I first noticed in IE7, and so when I went to debug (using IE8’s sweeter debugger), I noticed it even breaks in IE8.
It disregards completely the first <option>
in the string. Go ahead and try it yourself. Open IE8, press F12, go to Script, and try this super simple task:
var selectEl = document.createElement('select');
selectEl.innerHTML = '<option>this one breaks</option><option>we dont work because the first one is broken</option>';
document.body.appendChild(selectEl);
Solution
It breaks even that. So I resorted to DOM methods to build my select field.
for(var i = 0; i < item.options.length; i++) {
var option = document.createElement('option');
option.innerHTML = item.options[i];
select.appendChild(option);
}