[Javascript] deleting all options

Nick Fitzsimons nick at nickfitz.co.uk
Wed Feb 1 06:20:48 CST 2006


> i dynamically fill a <select> with options depending on an ID given by
> another <select>.
> when i do it twice the first created options still are in the new select.
>
> now i need ans easy function to clear the <select> of all its options.
>
> do i have to count through every option of that select or is there a
> faster way?

Assuming your select has an id, as in
<select id="mySelect">
you can use

// get reference to element
var element = document.getElementById("mySelect");
// remove all children of element
while (element.firstChild) {
   element.removeChild(element.firstChild);
}

As you presumably already have a variable reference to the select, adjust
accordingly.

The while loop there is a general purpose way of removing all the child
nodes of any element, so depending on your needs, you may find it useful
to move it into a function.

HTH,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/




More information about the Javascript mailing list