The :checked
selector can be used with document.querySelector
to retrieve the selected option.
let selectedText = document.querySelector('#selectId option:checked').text;
// or
let selectedText = document.querySelector('#selectId')
.querySelector('option:checked').text;
document.querySelector('button').addEventListener('click', function(e) {
console.log(document.querySelector('#selectId option:checked').text);
});
<select id="selectId">
<option>a</option>
<option>b</option>
<option>c</option>
</select>
<button>
Get selected text
</button>
For select elements with the multiple
attribute, document.querySelectorAll
can be used to obtain all selected options.
let selectedText = [...document.querySelectorAll('#selectId option:checked')]
.map(o => o.text);
document.querySelector('button').addEventListener('click', function(e) {
let selectedText = [...document.querySelectorAll('#selectId option:checked')]
.map(o => o.text);
console.log(selectedText);
});
<select id="selectId" multiple>
<option>a</option>
<option>b</option>
<option>c</option>
</select>
<button>
Get selected text
</button>