Categories
JavaScript Answers

How to add options to select with JavaScript?

Spread the love

To add options to select with JavaScript, we use the Option constructor.

For instance, we add a select element with

<select id="ageSelect">
  <option value="">Please select</option>
</select>

Then we write

const selectElement = document.getElementById("ageSelect");

for (let age = 12; age <= 100; age++) {
  selectElement.add(new Option(age));
}

to select the select element with getElementById.

Then we use a for loop to loop through the age values and then create a new option element with the Option constructor called with its text content value.

Then we call selectElement.add to add the option as the last child of the select drop down.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *