Categories
JavaScript Answers

How to Retrieve the Text of the Selected option Element in a select Element with JavaScript?

Spread the love

Sometimes, we want to retrieve the text of the selected option element in a select element with JavaScript.

In this article, we’ll look at how to retrieve the text of the selected option element in a select element with JavaScript.

Use the selectedIndex Property

We can get the index of the selected item with the selectedIndex property.

Then we can use the text property to get the text of the selected item.

For instance, if we have the following HTML:

<select>
  <option value="1">apple</option>
  <option value="2" selected>orange</option>
</select>

Then we can write the following JavaScript code to get the selected item from the select element:

const getSelectedText = (el) => {
  if (el.selectedIndex === -1) {
    return null;
  }
  return el.options[el.selectedIndex].text;
}

const select = document.querySelector('select')
const text = getSelectedText(select);
console.log(text)

We create the getSelectedText function that takes an element as the parameter.

Then we check if selectedIndex is -1.

If it’s -1, then nothing is selected and we return null .

Otherwise, we get the options with el.options .

And then we get the selected option by passing in the el.selectedIndex into the square brackets.

Finally, we get the text property to get the text of the selected option element.

Therefore, the console log should log 'orange' .

Conclusion

We can retrieve the text of a selected option element with the selectedIndex and text properties.

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 *