How to change the selected option of an HTML select element with JavaScript?

Spread the love

Sometimes, we want to change the selected option of an HTML select element with JavaScript.

In this article, we’ll look at how to change the selected option of an HTML select element with JavaScript.

How to change the selected option of an HTML select element with JavaScript?

To change the selected option of an HTML select element with JavaScript, we set the value property of the select element.

For instance, we write

<select id="sel">
  <option value="cat">Cat</option>
  <option value="dog">Dog</option>
  <option value="fish">Fish</option>
</select>

to add a select element.

Then we write

document.getElementById("sel").value = "dog";

to select the select element with getElementById.

Then we set its value property to the value attribute value of the option element we want to select.

Conclusion

To change the selected option of an HTML select element with JavaScript, we set the value property of the select element.

Leave a Reply

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