views:

53

answers:

2

hey, I've found some results for this on google but nothing satisfying so I was hoping someone here might know.

It seems as though populating a select element using innerHTML does not work in IE

I have set up a file that does nothing but that and it works with everything but IE, here's the code in case anyone cares:

<html>
<head></head>

<body onload="populate();">
<script type="text/javascript">
  function populate()
  {
    document.getElementById("test").innerHTML = '<option id="a">works</option>';
  }
</script>

<select id="test"></select>

</body>
</html>

Anyone know a solution to this? I don't want to remove everything and then manually use appendChild as I am returned html from a different function, and it seems ridiculous that this doesn't work.

Any ideas would be appreciated.

+3  A: 

EDIT: This answer was written before the OP said he didn't want to use appendChild(). I will keep this answer up for reference.


This post will use POJSF. (Plain Old JavaScript Framework, the framework every other framework is based on!)
For those who don't get it, that's a poor attempt a humor...

Instead of using innerHTML, you can create your <option> using document.createElement()

var newOption = document.createElement('option');
newOption.label = 'works';

newOption.appendChild(document.createTextNode(newOption.label));

newOption.id = 'a';

document.getElementById('mySelect').appendChild(newOption);

If you want to remove all <option> in a <select>:

var selectEl = document.getElementById('mySelect');
for(var i = selectEl.children.length - 1; i >= 0; i--) {
    selectEl.removeChild(selectEl.children[i]);
}
Andrew Moore
innerText is not supported by Firefox, see http://www.quirksmode.org/dom/w3c_html.html
karim79
**@karim79:** Thanks, fixed. InnerText is really just needed in IE6, so even if Firefox doesn't support it, it doesn't need it.
Andrew Moore
+1 - now that I didn't know.
karim79
**@karim79:** Only in Quirks mode and only in edge cases. Otherwise, the `.label` property works just fine.
Andrew Moore