+ 2
Removing all options from 'select' element HTML
Hello. What is the proper way to remove all option elements from a select box using javascript? I tried removeChild, remove, clear etc. I looked over examples on Google, but with no success. Thanks in advance.
5 Respuestas
+ 1
try this in codepen , it should work
<select id="brands">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
var select = document.getElementById("brands");
var length = select.options.length;
for (i = length-1; i >= 0;i--) {
select.remove(i);
}
+ 1
in the for loop condition against length normal scenario should be like below
for(i =0;i < length ; i++)
each time u remove the length is changed so
when i=0 length is 4 and index 0 is removed ,
i=1 new length is 3 and index 1 is removed ,
i=2 new length is 2 and the loop terminates as i is not less than length
0
@mostafa, there is a reason you chose to make a reverse for loop right?
Thank you for the answer
0
I understand, thank you very much!
0
i am not sure why length is changed every time :) , i am sure there is a better way