How to dynamically add options to an existing select in JavaScript?

Sometimes, we want to dynamically add options to an existing select in JavaScript.

In this article, we’ll look at how to dynamically add options to an existing select in JavaScript.

How to dynamically add options to an existing select in JavaScript?

To dynamically add options to an existing select in JavaScript, we can use a new Option object append it to the select element with the options.add method.

For instance, we write:

<select>

</select>

to add a select element.

Then we write:

const select = document.querySelector('select');
select.options.add(new Option('Text 1', 'Value1'))

to select the select element with document.querySelector.

Then we call select.options.add with the Option instance to add the option.

We pass in the option text and the value of the value attribute respectively to the Option constructor.

Conclusion

To dynamically add options to an existing select in JavaScript, we can use a new Option object append it to the select element with the options.add method.