How to add an item to dropdown list in HTML using JavaScript?

Sometimes, we want to add an item to dropdown list in HTML using JavaScript.

In this article, we’ll look at how to add an item to dropdown list in HTML using JavaScript.

How to add an item to dropdown list in HTML using JavaScript?

To add an item to dropdown list in HTML using JavaScript, we can use a for loop.

For instance, we write:

<select>

</select>

to add a select element.

Then we write:

const select = document.querySelector("select");
for (let i = 2022; i >= 1900; i--) {
  const option = document.createElement('option');
  option.text = option.value = i;
  select.add(option, 0);
}

to select the select element with document.querySelector.

And then we use a for loop to loop from 2022 to 1900.

In the loop, we create the option element with:

const option = document.createElement('option');

Then we set the text and value to set the text and the value attribute value respectively.

And then we call select.add to add the option into the select.

Conclusion

To add an item to dropdown list in HTML using JavaScript, we can use a for loop.