Read more

Selector for finding the currently selected option in a <select> tag

Arne Hartherz
December 09, 2021Software engineer at makandra GmbH

Use option:checked to find the currently selected option:

select.querySelector('option:checked')
Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

Yes, :checked, not :selected.

This is the same as finding an option with the { selected: true } property in JavaScript:

select.querySelectorAll('option').find((option) => option.selected)

What about the selected attribute?

Note that option[selected] would only find an <option selected> tag. This may be the selected option right after loading the page, but not once the user switched to a different value. It also won't work in JavaScript-heavy applications where you might not be rendering an option tag with the selected attribute in the first place.

Posted by Arne Hartherz to makandra dev (2021-12-09 11:51)