Categories
JavaScript Answers

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

Spread the love

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.

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 *