Working with dropdown list items in JavaScript

Let us have a reference to the option tag in a variable. For example, obtained as follows:

let select = document.querySelector('#select'); let option = select[0];

In this case, the text property will store the text of the option, the value property will store the value of the attribute of the same name, and the selected property will store the value of true or false depending on whether the list item is selected or not:

console.log(option.text); console.log(option.value); console.log(option.selected);

Go through the list items in a loop and add an exclamation mark to the end of the text for the selected item, and a question mark for unselected items.

Selecting a list item

In previous lessons, we accessed the select tag to get or change the selected list item. It's not really necessary. After all, you can directly set the property selected of some option tag to true.

For example, let's make the list item with number two selected:

let select = document.querySelector('#select'); let option = select[2]; option.selected = true;

Given a dropdown list and a button. By clicking on the button, make selected the last item in the list.

Getting the selected option

Using everything learned, you can get the selected option tag as follows:

let select = document.querySelector('#select'); console.log(select[select.selectedIndex]);

Given a select and a button. By pressing the button, display the text of the marked list item.

Given a select and a button. Add an exclamation mark to the end of the selected item text when you click the button.

enru