Emmanuel Akinfulubi

JavaScriptDOM

Remove the selected option from a dropdown in JavaScript

Intermediate · 3 min read

Dropdowns change while people use a page. A seat that has been booked disappears from the list, a tag you have already added can't be picked twice, a "remove" button takes an item out. Removing the selected option takes one line. Removing several at once hides a classic bug, and this lesson walks you straight into it so you will recognize it later.

In this tutorial you will remove the selected color from a dropdown when a button is pressed, then empty the whole list correctly. You should know what an HTML select is and what a for loop does.

The dropdown

index.html

<select id="colorSelect">
  <option>Red</option>
  <option>Green</option>
  <option>White</option>
  <option>Black</option>
</select>
<button id="go" type="button">Select and Remove</button>

options and selectedIndex

A select element gives you two things this exercise needs:

  • select.options is the list of its option elements, numbered from 0. Here options[0] is Red and options[3] is Black.
  • select.selectedIndex is the number of the option currently chosen. If nothing is chosen, for example because the list is empty, it is -1.

An option can remove itself from the page with option.remove().

Here is the exercise. Try it first if you want, or follow the steps.

8 Remove an item from a dropdown

fair

A select lists Red, Green, White and Black. Remove the selected one when the button is pressed.

Stuck? Three hints, smallest first
  1. 1. select.remove(index) or select.options[i].remove() both work.
  2. 2. After a removal every later index shifts down by one.
  3. 3. Removing while looping forwards skips items. Loop backwards, or filter first.

Step 1: remove the selected option

Step 1

const select = document.getElementById('colorSelect');
const names = (s) => [...s.options].map((o) => o.textContent);
select.selectedIndex = 2;           // pretend the user chose White
select.options[select.selectedIndex].remove();
console.log(names(select).join(', ')); // Red, Green, Black

names is a small helper that lists what is left. [...s.options] copies the options into a real array first, because options itself has no map method.

Look at what happened to Black. It was at position 3, and now it is at position 2. Everything after a removed option moves down one place to close the gap. Keep that in mind; it matters in Step 3.

Step 2: make it safe and connect the button

If the list is already empty, selectedIndex is -1 and options[-1] is undefined. Calling .remove() on that would throw. Check first:

Step 2

function removecolor(target) {
  const i = target.selectedIndex;
  if (i === -1) return null;        // nothing selected, nothing to do
  const removed = target.options[i].textContent;
  target.options[i].remove();
  return removed;
}
const select = document.getElementById('colorSelect');
select.selectedIndex = 0;
console.log(removecolor(select)); // Red

Returning the name of what was removed is useful for a message like "Removed Red". To run it on each click:

JavaScript

document.getElementById('go').addEventListener('click', () => removecolor(select));

Step 3: the wrong way to remove everything

Now suppose you want to empty the list. The obvious loop looks like this:

Step 3

const select = document.getElementById('colorSelect');
const names = (s) => [...s.options].map((o) => o.textContent);
for (let i = 0; i < select.options.length; i++) {
  select.options[i].remove();
}
console.log(names(select).join(', ')); // Green, Black

Half of them survive. Walk through it slowly:

  1. i is 0. Red is removed. Green slides down to position 0.
  2. i is 1. Position 1 is now White, so White is removed. Green was skipped.
  3. i is 2, but only two options are left, so the loop stops. Green and Black stay.

Each removal moves the rest down, while i keeps moving up, so every other option gets jumped over.

Step 4: loop backwards

Start at the end and count down instead:

Step 4

const select = document.getElementById('colorSelect');
for (let i = select.options.length - 1; i >= 0; i--) {
  select.options[i].remove();
}
console.log(select.options.length); // 0
console.log(select.selectedIndex);  // -1

Removing the last option never moves anything before it, so nothing is skipped. Once the list is empty, selectedIndex is -1, which is exactly the case Step 2 guards against.

Another safe way is to take a copy of the list first. The copy doesn't change as options are removed:

JavaScript

for (const option of [...select.options]) {
  if (option.textContent !== 'Red') option.remove();
}
// only Red is left

The live demo has a button for the forwards loop and one for the backwards loop, so you can watch the first one skip.

The full solution

The panel removes the selected option, then shows both loops side by side. Its checks confirm White goes, the indexes close up, the forwards loop leaves two behind, and the backwards loop and the copy both work. Press Run to see it.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

const makeSelect = () => el('select', { id: 'colorSelect' },
  ['Red', 'Green', 'White', 'Black'].map((c) => el('option', {}, c)));

let select = makeSelect();
document.body.appendChild(select);

// options is an HTMLOptionsCollection. It has length and indexing but no map,
// so it must be spread into a real array first.
const names = (s) => [...s.options].map((o) => o.textContent);

function removecolor(target) {
  const i = target.selectedIndex;
  if (i === -1) return null;                     // nothing selected, nothing to do
  const removed = target.options[i].textContent;
  target.options[i].remove();
  return removed;
}

console.log('start        :', names(select));
select.selectedIndex = 2;                        // White
console.log('removed      :', removecolor(select));
console.log('remaining    :', names(select));

// The classic mistake: removing while walking forwards.
const forwards = makeSelect();
for (let i = 0; i < forwards.options.length; i++) forwards.options[i].remove();
console.log('looped forwards, survivors:', names(forwards), '<- every other one');

// Backwards is safe, because removing index i does not move anything below it.
const backwards = makeSelect();
for (let i = backwards.options.length - 1; i >= 0; i--) backwards.options[i].remove();
console.log('looped backwards, survivors:', names(backwards));

Output


      
14 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 14 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

14 checks

test('it started with four options', 4, 4);
test('the selected one was removed', names(select), ['Red', 'Green', 'Black']);
test('three are left', select.options.length, 3);
test('and the indexes closed up', names(select)[2], 'Black');
test('removing again takes another', (() => { select.selectedIndex = 0; removecolor(select); return names(select); })(), ['Green', 'Black']);
test('emptying it completely leaves none', (() => { while (select.options.length) select.options[0].remove(); return select.options.length; })(), 0);
test('and selectedIndex becomes -1', select.selectedIndex, -1);
test('so removing from an empty select is safe', removecolor(select), null);
test('looping FORWARDS leaves half behind', names(forwards), ['Green', 'Black']);
test('which is a bug, not a feature', forwards.options.length === 0, false);
test('looping BACKWARDS removes them all', names(backwards), []);
test('a static copy is the other safe way', (() => { const s = makeSelect(); for (const o of [...s.options]) if (o.textContent !== 'Red') o.remove(); return names(s); })(), ['Red']);
test('options is not an array', Array.isArray(makeSelect().options), false);
test('so .filter would throw on it', typeof makeSelect().options.filter, 'undefined');

The removal itself is one line. The exercise is really about the loop. Removing index 0 shifts everything down, so the next pass at index 1 is looking at what used to be index 2 — the assertions show four options becoming two rather than none. Loop backwards, because removing index i never moves anything below it. The live demo has a button for each so you can watch the wrong one skip.

The same trap applies to splice inside a forward for loop over an array, and to any live DOM collection like getElementsByTagName. Either iterate backwards or take a static copy first with [...collection].

Common mistakes

  • Removing while looping forwards. Each removal shifts the rest down, so every other item is skipped. Loop backwards, or loop over a copy.
  • Not checking for -1. On an empty list selectedIndex is -1, and options[-1].remove() throws.
  • Calling filter on options. It is a collection, not an array. Spread it first: [...select.options].filter(...).

Try it yourself

  1. After each removal, show "Removed White, 3 left" in a paragraph under the dropdown.
  2. Disable the button when the list is empty, by setting button.disabled = true.
  3. Add a text box and an "Add" button that puts a new option at the end, using select.add(new Option(text)).

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.