- 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?
- How to get DOM elements using JavaScript
- You might also like.
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 17, 2023 by MDN contributors.
Your blueprint for a better internet.
How to get DOM elements using JavaScript
The Document Object Model (DOM) is a programming interface for HTML and XML documents created by the browser once the document is loaded. A web page is a document represented by the DOM as nodes and objects. It allows programs to manipulate the document’s content, structure, and styles.
In this tutorial, we shall learn how to use JavaScript to access different nodes (HTML elements) in the DOM. Let us start with the first method: getting an element by ID.
The document ‘s getElementById() method takes the element ID as input and returns an Element object representing the DOM element. Here is an example:
const unicorn = document.getElementById('unicorn')
The ID is case-sensitive and unique across the entire HTML document. So this method always returns a single element. If no matching element is found, it returns null .
Note: Do not put the # sign before the ID string while calling getElementById() method. You will get null instead of the element, and then you might wonder for hours what has gone wrong.
The getElementsByTagName() method is used to access multiple elements. It takes the tag name as input and returns all of the DOM elements that match the tag name as HTMLCollection :
JavaScript code to access all
elements:
const animals = document.getElementsByTagName('p')
This method searches only one tag name at a time. But if you pass in * as the tag name, you will get all elements in the DOM:
const allNodes = document.getElementsByTagName('*')
The getElementsByName() method is used to get a collection of elements by their name attribute and returns a NodeList object:
input type="text" name="email"> input type="tel" name="phone"> input type="date" name="dob">
const emails = document.getElementsByName('email')
Note: Unlike the id attribute, which must be unique, multiple HTML elements can have the same name attribute. That’s why getElementsByName() returns a collection of nodes.
Want to use the class attribute to get a list of matching elements? You can use the getElementsByClassName() method, pass it a class name (without . ), and it will return an HTMLCollection of all DOM elements that have the given class name:
div class="bird owl">🦉div> div class="bird">🐦div> div class="bird eagle">🦅div> div class="animal cat">🐱div>
const birds = document.getElementsByClassName('bird')
This method also accepts multiple class names separated by spaces. Let us get all elements that have both the bird and eagle classes:
const eagle = document.getElementsByClassName('bird eagle')
The querySelector() method is one of the two modern JavaScript methods that allow you to get elements from DOM based on CSS selectors. Just pass in the CSS selector, and you will get the first element that matches the specified selector. If no matches exist, it returns null . Here is an example:
const email = document.querySelector('#signup input[name="email"]')
Want to select a list of elements that match the specified selectors? Use the querySelectorAll() method instead. This method takes multiple CSS selectors as input and returns a NodeList , a list of DOM elements that match the given selectors. Let us select all elements with a class of either bird or animal from the above HTML markup:
const elems = document.querySelectorAll('.bird, .animal') console.log(elems.length) // 4
You can also chain multiple functions together to search elements within another element. You first need to select a single element using either getElementById() or querySelector() and then chain another function to search within:
form id="signup"> input type="text" name="email"> input type="tel" name="phone"> input type="date" name="date-of-birth"> form>
const inputs = document.getElementById('signup').getElementsByTagName('input') // OR const inputs = document.querySelector('#signup').querySelectorAll('input')
Most of the methods we discussed above (except getElementById() and querySelector() ) returns multiple elements as either an HTMLCollection or a NodeList . The HTMLCollection is not an array but a generic collection of elements. So it is impossible to iterate over it with the forEach() or map() method. However, we can convert it to a real array and then iterate using the Array.from() method:
const inputs = document.getElementById('signup').getElementsByTagName('input') // iterate over HTMLCollection Array.from(inputs).forEach(element => console.log(element) >)
Although NodeList is also not an array, it does provide the forEach() method to iterate over the elements:
const inputs = document.querySelector('#signup').querySelectorAll('input') //iterate over NodeList inputs.forEach(element => console.log(element) >)
That’s all for getting DOM elements using JavaScript. We have learned about many different methods to access the DOM elements: using the id attribute, HTML tag name, name attribute, class attribute, and CSS selectors. We also discussed ways to iterate over the generic collection of elements returned by these methods. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.