AL-zami AL-zami - 1 year ago 125
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) => {



Answer Source

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--;) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download