+ 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.

27th May 2017, 5:45 AM
Shahar Levy
Shahar Levy - avatar
5 odpowiedzi
+ 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); }
27th May 2017, 9:06 AM
Gohary
Gohary - avatar
+ 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
27th May 2017, 2:21 PM
Gohary
Gohary - avatar
0
@mostafa, there is a reason you chose to make a reverse for loop right? Thank you for the answer
27th May 2017, 2:06 PM
Shahar Levy
Shahar Levy - avatar
0
I understand, thank you very much!
27th May 2017, 2:23 PM
Shahar Levy
Shahar Levy - avatar
0
i am not sure why length is changed every time :) , i am sure there is a better way
27th May 2017, 2:23 PM
Gohary
Gohary - avatar