Faster way to populate <select> with Javascript Faster way to populate <select> with Javascript ajax ajax

Faster way to populate <select> with Javascript


500 elements is not a lot, even for IE. You must be doing something else to cause the lag.

I just tried with 500+ options in IE6, IE7, FF2 and FF3 and all were near instantaneous. I used this code:

var data = [    { text: 'foo', value: 'bar' },    // ...    { text: 'foo', value: 'bar' }];var select = document.getElementsByTagName('select')[0];select.options.length = 0; // clear out existing itemsfor(var i=0; i < data.length; i++) {    var d = data[i];    select.options.add(new Option(d.text, i))}

I would suggest profiling the bit of code that is fetching the data and populating the drop down. Something else might be taking up the time. For example, check that the code that "breaks up" the string value returned from the server is sharp (sounds like you're doing your own custom parsing there).


The first code is fine but this works better for me:

var data = [    { text: 'uno', value: '1' },    {text: 'dos', value: '2' }];var select = document.getElementById('select-choice-1');select.options.length = 0; // clear out existing itemsfor (var i = 0; i < data.length; i++) {    var d = data[i];    select.options.add(new Option(d.text, d.value))}


Setting it using SelectElement.innerHTML would be the fastest... but that FAILS in IE.

Last I checked, you can do this in IE, if you wrap all the options in a bogus <div> tag, or set the entire .outerHTML of the select list in IE.