Clearing options AND optgroups in a select

Until today, I always cleared options from a select by doing something like this:

JavaScript:
  1. //Clear select of exiting options
  2. element.options.length = 0;

A quick Google search turned up this blog post where they had this helpful snippet:

JavaScript:
  1. //Clear select of exiting options and optgroups
  2. while (element.hasChildNodes()) {
  3.      element.removeChild(element.firstChild);
  4. }

This clears all items in the select and there is no noticeable performance loss when dealing with a select with a reasonable number of options.

Leave a Reply

You must be logged in to post a comment.