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

Posted Over 2 years ago. Visible to the public.

Use option:checked to find the currently selected option:

select.querySelector('option:checked')

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.

Arne Hartherz
Last edit
Over 2 years ago
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2021-12-09 10:51)