Remove all Listbox and Dropdown List Items with jQuery CodeUnit 27 FEB 2010

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.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • robvdv

    You can do it even more succinctly: $('select option').remove();

  • Absolutely robvdv, far more succinct and beautiful to look at, though doing it the long way around as indicated in the post does allow you to add in extra logic in the each() function, for example allowing you to skip the removal of specific options.

  • Loony2nz

    here’s a monkey wrench for you :)

    How do you QUICKLY remove all the items in a dropdown list when there are hundreds of options?

    I have a dynamic dropdown list that needs to be cleared and populated based on the selection of another dropdown item. When the ajax rendered dropdown has hundreds of options to clear out and get repopulated, it takes quite some time to remove the items (populating it is quick though).

    I’ve tried adding a class to each option and remove those class items. This is probably the worst way.

    I’ve tried .empty() and .remove() and .removeOption(). All have the same slow performance issue.

    Is this just the nature of the DOM or is there something else that I’m missing.


  • Gerardo Grimaldi

    Very useful,  thanks!

  • jai

    how to clear all the items in the listbox by clicking on the button… Thanks in advance…