Count the options in a dropdown in JavaScript
Beginner · 3 min read
How many items are in this list, and what are they? You need the answer to show "4 colors available", to check a list loaded properly, or to send the choices somewhere else. For a dropdown it is a short job, and it teaches two things you will use with every list on a page.
In this tutorial you will count the options in a select and build a message like 4 items: Red, Green, Blue, White. You should know what an HTML dropdown is and have seen an array's map and join.
The dropdown
<select id="mySelect">
<option>Red</option>
<option>Green</option>
<option>Blue</option>
<option>White</option>
</select>
select.options holds the four option elements, numbered from 0. Each option's textContent is the text you see in the list.
A collection is not an array
select.options has a length, and you can read options[0], so it looks like an array. It isn't. It is a collection, a list type the browser uses for elements, and it has no map, filter or join. To use those, copy it into a real array with the spread syntax, [...select.options], or with Array.from(select.options).
Here is the exercise. The quick way to show the answer would be an alert pop-up; here you return the text instead, so it can be checked and shown on the page.
9 Count the items in a dropdown
easyCount the options in a select and display them. The usual version uses alert; return the text instead so it can be checked.
Stuck? Three hints, smallest first
- 1.
select.options.lengthis the count.select.lengthgives the same number. - 2.
optionsis a collection, not an array, so spread it before usingmap. - 3. An option’s
textand itsvalueare different things when avalueattribute is present.
Step 1: count them
const select = document.getElementById('mySelect');
console.log(select.options.length); // 4
console.log(select.length); // 4
Both give the same number. select.length is a shortcut for select.options.length.
Step 2: read the names
The obvious move is to call map on the options. Try it:
const select = document.getElementById('mySelect');
console.log(Array.isArray(select.options)); // false
console.log(typeof select.options.map); // undefined
select.options.map(...) would throw a TypeError, because there is no map to call. Spread it into an array first:
const select = document.getElementById('mySelect');
const items = [...select.options].map((o) => o.textContent);
console.log(items.join(', ')); // Red, Green, Blue, White
[...select.options] makes a real array of the four option elements. map then turns each element into its text, and join(', ') glues the texts into one string.
Step 3: build the message in a function
Put it together in a function that returns the count, the names and a readable message:
function getOptions(target) {
const items = [...target.options].map((o) => o.textContent);
return { count: target.options.length, items, message: `${items.length} items: ${items.join(', ')}` };
}
const result = getOptions(document.getElementById('mySelect'));
console.log(result.count); // 4
console.log(result.message); // 4 items: Red, Green, Blue, White
Returning the message, rather than calling alert, means the caller decides what to do with it: put it on the page, log it, or test it. An alert freezes the whole page until someone clicks OK. The live demo writes the message into the page instead.
An empty dropdown works too: the count is 0 and the message is 0 items: with nothing after it.
Step 4: text and value are different things
An option can have a value attribute. When it does, the text people see and the value the form sends are different:
const withValues = document.getElementById('cities');
console.log([...withValues.options].map((o) => o.textContent).join(', ')); // Lagos, Abuja
console.log([...withValues.options].map((o) => o.value).join(', ')); // LOS, ABV
Here cities is a second dropdown on the page:
<select id="cities">
<option value="LOS">Lagos</option>
<option value="ABV">Abuja</option>
</select>
Use the text when you show the choices to a person, and the value when you store or send them. Without a value attribute, the two are the same string.
The collection keeps up by itself
Add a fifth option and ask again. You don't need to look up the dropdown again:
const select = document.getElementById('mySelect');
const extra = document.createElement('option');
extra.textContent = 'Black';
select.appendChild(extra);
console.log(select.options.length); // 5
select.options always reflects what is in the dropdown right now.
The full solution
The panel builds both dropdowns and prints the message, the two counts, and the texts next to the values. Its checks confirm the count, the order, the empty case, that options isn't an array until you spread it, and that adding an option changes the count. Press Run to see it.
allow-scripts only, so it cannot reach this page.const select = el('select', { id: 'mySelect' },
['Red', 'Green', 'Blue', 'White'].map((c) => el('option', {}, c)));
document.body.appendChild(select);
// An option whose visible text differs from its submitted value.
const withValues = el('select', {}, [
el('option', { value: 'LOS' }, 'Lagos'),
el('option', { value: 'ABV' }, 'Abuja'),
]);
document.body.appendChild(withValues);
function getOptions(target) {
const items = [...target.options].map((o) => o.textContent);
// The usual version calls alert(). Returning the message is the same information
// without freezing the page, and it can be asserted.
return { count: target.options.length, items, message: `${items.length} items: ${items.join(', ')}` };
}
const result = getOptions(select);
console.log(result.message);
console.log('options.length:', select.options.length, ' select.length:', select.length);
console.log('--- text is not always the value ---');
console.log('texts :', [...withValues.options].map((o) => o.textContent));
console.log('values:', [...withValues.options].map((o) => o.value));
console.log('an empty select counts 0:', el('select', {}).options.length);
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.
test('four options are counted', result.count, 4);
test('select.length agrees', select.length, select.options.length);
test('the names are read in order', result.items, ['Red', 'Green', 'Blue', 'White']);
test('the message reads properly', result.message, '4 items: Red, Green, Blue, White');
test('an empty select counts zero', getOptions(el('select', {})).count, 0);
test('and its message says so', getOptions(el('select', {})).message, '0 items: ');
test('options is a collection, not an array', Array.isArray(select.options), false);
test('so it has no map method', typeof select.options.map, 'undefined');
test('but spreading gives a real array', Array.isArray([...select.options]), true);
test('which does have map', typeof [...select.options].map, 'function');
test('text and value differ when value is set', [...withValues.options].map((o) => o.value), ['LOS', 'ABV']);
test('while the text is what the reader sees', [...withValues.options].map((o) => o.textContent), ['Lagos', 'Abuja']);
test('adding an option changes the count', (() => { select.appendChild(el('option', {}, 'Black')); return select.options.length; })(), 5);
test('and the collection reflects it immediately', getOptions(select).items.at(-1), 'Black');
Adapted. The original pops the answer up in an alert. An alert cannot be asserted, it blocks the whole page, and it is genuinely unpleasant, so this returns the message and the demo writes it into the page. Same information, no modal.
select.options is an HTMLOptionsCollection, not an array — the assertion checks Array.isArray is false. It has length and indexing, so it looks like an array until you reach for map or filter and get a TypeError. [...collection] or Array.from(collection) fixes it. It is also live: the last two assertions add an option and see the count change with no re-query.
Keep option.text and option.value apart. The text is what the reader picks; the value is what gets submitted. They are the same string only while no value attribute is set.
Common mistakes
- Calling
maponselect.options. It is a collection, not an array. Use[...select.options].map(...). - Mixing up text and value.
textContentis what the reader sees;valueis what gets submitted. They differ when avalueattribute is set. - Using
alertto show the result. It blocks the page and can't be tested. Return the text and put it on the page.
Try it yourself
- Count only the options whose text is longer than four letters, using
filter. - Show the message in a paragraph every time the user picks a different color, using the
changeevent on the select. - Return the selected option's text too, using
select.options[select.selectedIndex].