Removing options from Select tag in Vanilla JavaScript with "for .. of" loop

You're removing items from an array, as you iterate through the array. So you have:

["one","two","three"]

then you remove the item at index 0, which is "one," leaving you with:

["two","three"]

next you remove the item at index 1, which is "three," leaving you with:

["two"]

there is no item at index 2, so the loop stops.

Iterate through the array in reverse instead:

const t = document.querySelector("#form-select")

for (let i = t.options.length-1; i >= 0; i--) {
  t.removeChild(t.options[i])
}
<select id="form-select">
  <option>111</option>
  <option>222</option>
  <option>333</option>
</select>

The .options collection is (unfortunately) live, so iterating over the live collection's items one-by-one and .removeing every one will result in every odd one being kept. (Eg, right when you remove the first item, the [0]th item of the collection will immediately become the next item in the collection - what used to be [1] will become [0] (and then once you go to the next index at [1], the new item at position 0 won't be iterated over)

Use document.querySelectorAll instead, which returns a collection which is static:

for (const option of document.querySelectorAll('#form-select > option')) {
  option.remove();
}
<select id="form-select">
  <option>111</option>
  <option>222</option>
  <option>333</option>
</select>

You can also spread into a (static) array before removing elements::

for (const option of [...document.querySelector('#form-select').options]) {
  option.remove();
}
<select id="form-select">
  <option>111</option>
  <option>222</option>
  <option>333</option>
</select>

Another option which just happens to work because the collection is live (but probably shouldn't be used, since it's not intuitive):

const { options } = document.querySelector('#form-select');
while (options.length) {
  options[0].remove();
}
<select id="form-select">
  <option>111</option>
  <option>222</option>
  <option>333</option>
</select>

Tags:

Javascript