AL-zami AL-zami - 1 month ago 4x
Javascript Question

remove all options from select tag

Here i have a select element and couple of option elements.I want to delete all option elements by running a foreach loop on them.But only first two elements are getting removed.What is wrong with this code?

<!DOCTYPE html>
<p id='item'></p>
remove all from fruit list:
<select id="mySelect" size="4" class='myclass' onChange='myFunction(this.className);'>
<option id='for_apple'>Apple</option>

let select_item = document.getElementById('mySelect');
let options=select_item.getElementsByTagName('option');
console.log('length is : '+options.length);,(elem,index,arr) => {




Nodelists are "live", so when you iterate over them, the length changes and the loop stops.

The solution is to iterate backwards

let select_item = document.getElementById('mySelect');
let options = select_item.getElementsByTagName('option');

for (var i=options.length; i--;) {