Manipulation of HTML Select Element with Javascript

Use-Cases of this Tutorial

You are looking to know the Javascript methods you can use on select (dropdown) element.

You are looking to know how to add or remove an option in a dropdown.

You are looking to know how to get or set selected options in a dropdown.

Manipulation of the <select> element with Javascript is quite commonly required in web applications. This tutorial explains how you can perform common operations on select element with vanilla Javascript — adding/deleting options or getting/setting the selected options.

Important Properties and Methods of Select Element

value : It gives the value of the first selected option (a multi-valued select may have multiple selected options)

options : It gives the list of all option elements in the select

selectedOptions : It gives the list of option elements that are currently selected

selectedIndex : It is an integer that gives the index of first selected option. In case no option is selected, it gives -1

add() : This method adds a new option to the list of options

remove() : This method removes an option from the select element

Important Properties of Option Element

value : It gives the value of the option

text : It gives the text inside the option

selected : It tells whether the option is selected or not

Setting Value of Select Element

For a single valued select, setting its value can be done with the value or the selectedIndex property.

This will obviously work for single valued select also, but using the value property is much direct for them.

Getting the Value and Text/Label of the Selected Options

The selectedOptions property of the select element gives the list of options that are currently selected. Each element in this list is a DOM <option> element — so you can use the value and text property to get the value and inside text of the option.

// For a normal select (and not multi-select) the list would contain only a single element
var text = document.querySelector('#choose-fruit').selectedOptions[0].text;
var value = document.querySelector('#choose-fruit').selectedOptions[0].value;

For a multiple select element, you can loop over the list to get all selected options.