AL-zami AL-zami - 2 months ago 7
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>
<html>
<body>
<p id='item'></p>
<form>
remove all from fruit list:
<br>
<select id="mySelect" size="4" class='myclass' onChange='myFunction(this.className);'>
<option id='for_apple'>Apple</option>
<option>Pear</option>
<option>Banana</option>
<option>Orange</option>
</select>



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

console.log(options.length);
select_item.removeChild(elem);
});
</script>

</body>
</html>

Answer

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--;) {
    select_item.removeChild(options[i]);
}
Comments