I’ve said it once and I’ll say it a million times over and again, the jQuery javascript library is simply fantastic. Today’s little code snippet is going to look at removing all the options from a select dropdown list or listbox, on the fly and using jQuery.

To get this little trick working, we are going to be making use of the remove() function that allows us to strip the target out of the pages DOM, essentially removing it from view and access.

In order to do this, we will construct a selector that will locate the target list using its ID value and then filter it down to all of its option children. Traversing through each option using the handy each() function, we will then apply a remove() call, essentially dropping that specific option out of the list, and in the end, leaving us with an empty <select> construct. Nice.

So the snippet to do this then would look a little something like this:

$('#selectlist option').each(function(i, option){ $(option).remove(); });

You can probably simplify the above by shortening the call logic and letting jQuery handle all the internals for you, but leaving it in the form that the example is currently in shows you exactly step for step how we are setting about achieving our desired empty state.

Magic I tell you.