I wonder if it's possible in Javascript to get the currently selected options in a <select multiple>
field using the Selctors API rather than a "stupid" iteration over all options.
select.querySelectorAll('option[selected="selected"]')
only returns the options that were marked as preselected in the original HTML, which is not what I'm looking for. Any ideas?
The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
Originally Answered: Why is my querySelectorAll() method not working ? The reason is that you try to access DOM elements before they are part of the DOM. There is no reason to use the querySelector at all unless you have a table already you want to modify.
The JavaScript querySelectorAll method is used to select elements in the document using CSS selectors and returns all the matching elements as a list. The method returns a static NodeList (an array-like object) that contains a list of all elements that match the specified selectors or group of selectors.
Definition and Usage. The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.
We can get the selected option element from the select element with the value property, which has the value of the value attribute of the selected option element. We can also get all the options with the options property. selectedIndex gets the index of the selected option element.
const select = document.querySelector ("select"); const selectedChoice = select.value; console.log (selectedChoice) to get the select element with document.querySelector . Then we get the value of the value attribute of the select option element with the value property. And then we should see that selectedChoice is 2.
document.querySelectorAll('option:checked')
Works even on IE9 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With