- Element: querySelectorAll() method
- Syntax
- Parameters
- Return value
- Exceptions
- Examples
- dataset selector & attribute selectors
- Obtaining a list of matches
- Accessing the matches
- Selector scope
- HTML
- JavaScript
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Manipulation of HTML Select Element with Javascript
- Important Properties and Methods of Select Element
- Important Properties of Option Element
- Setting Value of Select Element
- Getting the Value and Text/Label of the Selected Options
- Adding an Option
- Deleting an Option
Element: querySelectorAll() method
The Element method querySelectorAll() returns a static (not live) NodeList representing a list of elements matching the specified group of selectors which are descendants of the element on which the method was called.
Syntax
querySelectorAll(selectors)
Parameters
A string containing one or more selectors to match against. This string must be a valid CSS selector string; if it’s not, a SyntaxError exception is thrown. See Locating DOM elements using selectors for more information about using selectors to identify elements. Multiple selectors may be specified by separating them using commas.
Note that the selectors are applied to the entire document, not just the particular element on which querySelectorAll() is called. To restrict the selector to the element on which querySelectorAll() is called, include the :scope pseudo-class at the start of the selector. See the selector scope example.
Note: Characters which are not part of standard CSS syntax must be escaped using a backslash character. Since JavaScript also uses backslash escaping, special care must be taken when writing string literals using these characters. See Escaping special characters for more information.
Return value
A non-live NodeList containing one Element object for each descendant node that matches at least one of the specified selectors.
Note: If the specified selectors include a CSS pseudo-element, the returned list is always empty.
Exceptions
Thrown if the syntax of the specified selectors string is not valid.
Examples
dataset selector & attribute selectors
section class="box" id="sect1"> div class="funnel-chart-percent1">10.900%div> div class="funnel-chart-percent2">3700.00%div> div class="funnel-chart-percent3">0.00%div> section>
// dataset selectors const refs = [ . document.querySelectorAll(`[data-name*="funnel-chart-percent"]`), ]; // attribute selectors // const refs = [. document.querySelectorAll(`[class*="funnel-chart-percent"]`)]; // const refs = [. document.querySelectorAll(`[class^="funnel-chart-percent"]`)]; // const refs = [. document.querySelectorAll(`[class$="funnel-chart-percent"]`)]; // const refs = [. document.querySelectorAll(`[class~="funnel-chart-percent"]`)];
Obtaining a list of matches
const matches = myBox.querySelectorAll("p");
const matches = myBox.querySelectorAll("div.note, div.alert");
Here, we get a list of the document’s
elements whose immediate parent element is a with the class «highlighted» and which are located inside a container whose ID is «test» .
const container = document.querySelector("#test"); const matches = container.querySelectorAll("div.highlighted > p");
const matches = document.querySelectorAll("iframe[data-src]");
Here, an attribute selector is used to return a list of the list items contained within a list whose ID is «userlist» which have a «data-active» attribute whose value is «1» :
const container = document.querySelector("#userlist"); const matches = container.querySelectorAll("li[data-active='1']");
Accessing the matches
Once the NodeList of matching elements is returned, you can examine it just like any array. If the array is empty (that is, its length property is 0 ), then no matches were found.
Otherwise, you can use standard array notation to access the contents of the list. You can use any common looping statement, such as:
const highlightedItems = userList.querySelectorAll(".highlighted"); highlightedItems.forEach((userItem) => deleteUser(userItem); >);
Note: NodeList is not a genuine array, that is to say it doesn’t have array methods like slice , some , map , etc. To convert it into an array, try Array.from(nodeList) .
Selector scope
The querySelectorAll() method applies its selectors to the whole document: they are not scoped to the element on which the method is called. To scope the selectors, include the :scope pseudo-class at the start of the selector string.
HTML
In this example the HTML contains:
- two buttons: #select and #select-scope
- three nested elements: #outer , #subject , and #inner
- a element which the example uses for output.
button id="select">Selectbutton> button id="select-scope">Select with :scopebutton> div id="outer"> .outer div id="subject"> .subject div id="inner">.innerdiv> div> div> pre id="output">pre>
div margin: 0.5rem; padding: 0.5rem; border: 3px #20b2aa solid; border-radius: 5px; font-family: monospace; > pre, button margin: 0.5rem; padding: 0.5rem; >
JavaScript
In the JavaScript, we first select the #subject element.
When the #select button is pressed, we call querySelectorAll() on #subject , passing «#outer #inner» as the selector string.
When the #select-scope button is pressed, we again call querySelectorAll() on #subject , but this time we pass «:scope #outer #inner» as the selector string.
const subject = document.querySelector("#subject"); const select = document.querySelector("#select"); select.addEventListener("click", () => const selected = subject.querySelectorAll("#outer #inner"); output.textContent = `Selection count: $selected.length>`; >); const selectScope = document.querySelector("#select-scope"); selectScope.addEventListener("click", () => const selected = subject.querySelectorAll(":scope #outer #inner"); output.textContent = `Selection count: $selected.length>`; >);
Result
When we press «Select», the selector selects all elements with an ID of inner that also have an ancestor with an ID of outer . Note that even though #outer is outside the #subject element, it is still used in selection, so our #inner element is found.
When we press «Select with :scope», the :scope pseudo-class restricts the selector scope to #subject , so #outer is not used in selector matching, and we don’t find the #inner element.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
- Locating DOM elements using selectors
- Attribute selectors in the CSS Guide
- Attribute selectors in the MDN Learning Area
- Element.querySelector()
- Document.querySelector() and Document.querySelectorAll()
- DocumentFragment.querySelector() and DocumentFragment.querySelectorAll()
Found a content problem with this page?
This page was last modified on Jul 22, 2023 by MDN contributors.
Your blueprint for a better internet.
Manipulation of HTML Select Element with Javascript
Manipulation of the element with Javascript is quite commonly required in web applications. This tutorial explains how you can perform common operations on select element with vanilla Javascript — adding/deleting options or getting/setting the selected options.
Important Properties and Methods of Select Element
- value : It gives the value of the first selected option (a multi-valued select may have multiple selected options)
- options : It gives the list of all option elements in the select
- selectedOptions : It gives the list of option elements that are currently selected
- selectedIndex : It is an integer that gives the index of first selected option. In case no option is selected, it gives -1
- add() : This method adds a new option to the list of options
- remove() : This method removes an option from the select element
Important Properties of Option Element
- value : It gives the value of the option
- text : It gives the text inside the option
- selected : It tells whether the option is selected or not
Setting Value of Select Element
For a single valued select, setting its value can be done with the value or the selectedIndex property.
// Set option with value 'Orange' as selected document.querySelector('#choose-fruit').value = 'Orange'; // Set the option with index 2 as selected => Sets the 'Banana' option as selected document.querySelector('#choose-fruit').selectedIndex = 2;
For a multiple valued select, setting multiple selected options can be done by setting the selected attribute of the required option.
// choose the first option document.querySelector('#choose-fruit-multiple').options[0].selected = true; // also choose the third option document.querySelector('#choose-fruit-multiple').options[2].selected = true;
This will obviously work for single valued select also, but using the value property is much direct for them.
Getting the Value and Text/Label of the Selected Options
The selectedOptions property of the select element gives the list of options that are currently selected. Each element in this list is a DOM element — so you can use the value and text property to get the value and inside text of the option.
// For a normal select (and not multi-select) the list would contain only a single element var text = document.querySelector('#choose-fruit').selectedOptions[0].text; var value = document.querySelector('#choose-fruit').selectedOptions[0].value;
For a multiple select element, you can loop over the list to get all selected options.
var selected_options = document.querySelector('#choose-fruit-multiple').selectedOptions; for(var i=0; i // output Orange 2 Grapes 5
Adding an Option
The add method can be used to add a new option in the select. You can also specify the exact positon where the option needs to be inserted.
var option = document.createElement('option'); option.text = 'BMW'; // append option at the end // new options will be Volvo, Audi, Mercedes & BMW document.querySelector('#choose-car').add(option, null);
var option = document.createElement('option'); option.text = 'BMW'; // append option before index 0 // new options will be BMW, Volvo, Audi & Mercedes document.querySelector('#choose-car').add(option, 0);
var option = document.createElement('option'); option.text = 'BMW'; // append option before index 2 // new options will be Volvo, Audi, BMW & Mercedes document.querySelector('#choose-car').add(option, 2);
Deleting an Option
The remove method can be used to delete an option at a specified index.
// remove the option at index 1 // new options will be Volvo & Mercedes document.querySelector('#choose-car').remove(1);