How to set options of a dropdown using JavaScript?

Sometimes, we want to set options of a dropdown using JavaScript.

In this article, we’ll look at how to set options of a dropdown using JavaScript.

How to set options of a dropdown using JavaScript?

To set options of a dropdown using JavaScript, we can set the value property of the select element.

For instance, we write:

<select>
  <option value='apple'>Apple</option>
  <option value='orange'>Orange</option>
  <option value='grape'>Grape</option>
</select>

to add a select element.

Then we write:

const select = document.querySelector("select")
select.value = "orange";

to select the select element with querySelector.

And then we set select.value to 'orange' to select the 2nd choice.

We set value to a value that of value attribute in the option element.

Conclusion

To set options of a dropdown using JavaScript, we can set the value property of the select element.