Example of Removing Options From a Drop-Down List
How To Remove Options
The standard way to clear all the options is to simply set the
options.length property to zero. That function is listed below, and is fast enough when there are not that many options in the drop-down list (a.k.a. select boxes). This method is also the most browser-compatible. By clicking the the ‘add options’ and ‘remove options’ button above, you can see the required processing time in milliseconds.
There are many sample codes on the Internet that loop through all the options in a for loop. Each option is removed one at a time with a call to
remove or by setting them to
null. This is unnecessary at best, and slow and inefficient at best. The simple method requires fewer lines of code and runs faster.
I tried and timed various methods, such as hiding/showing and disabling/enabling the drop-down list. Finally, I came up the idea of removing the drop-down list completely, and adding back an empty copy of the original one. This is possible with calls to
replaceChild on the document object. The removed HTMLSelectElement (with all it’s options) is simply discarded, and the memory is freed by the browser when doing garbage collection. A new one is shallow cloned from the old one, and inserted back into the page. This is a O(1) or constant time operation. The deletion is offloaded into the browser’s back-end garbage collection thread, which allows the UI to continue operating at full-speed. The function is suitable for very large select boxes.
In IE 6, the standard method has the annoying effect of scrolling through the options while they are being erased. The fast method avoids this.
The alternate fast method was provided by Victor T., and it has not been tested in all browsers, but seems to work well and be simpler.
References to the original SELECT object will become invalidated! If you had created references to the select object in your code, make sure to re-initialize those references again after calling the function. This is because the function will destroy the original SELECT object. The function returns a reference to the new SELECT object.
You should set a fixed width, so that the list does not annoyingly change size as options are added and removed. An example is below.
<select id="MySelect" size="5" style="width:50ex;"> <option>This dropdown will be filled/emptied</option> </select> <input type="button" value="fast remove" onclick="ClearOptionsFast('MySelect');">
Don’t you wish you could append the above functions prototype of the HTMLSelectElement element? Unfortunately, IE 6 and 7 will not allow you to do that, so you will have to stick with the above stand-alone functions for now. The above code was tested in IE6, FireFox 3, and Opera 9.1.
Disclaimer: This content is provided as-is. The information may be incorrect.