document.querySelectorAll() Since: Selectors API(2008)
Uses a CSS selector to retrieve all HTML elements in the document that match the given condition. The return value is a NodeList object. See the overview for details on the NodeList object.
Syntax
// Retrieves from the entire document.
var elements = document.querySelectorAll("selector");
// Retrieves from within a specific HTML element.
var elements = parentElement.querySelectorAll("selector");
Arguments
| Argument | Description |
|---|---|
| selector | Specifies a CSS selector string. Any selector format that can be used in CSS is accepted. You can also specify multiple selectors separated by commas. |
Return Value
Returns a NodeList object containing all HTML elements that match the condition. The NodeList object can be treated like an array. If no matching HTML elements exist, an empty NodeList is returned.
Sample Code
<ul> <li class="item">Apple</li> <li class="item">Orange</li> <li class="item">Grape</li> </ul>
// Retrieves all li elements.
var items = document.querySelectorAll(".item");
console.log(items.length); // Outputs "3".
// Loops through with forEach.
items.forEach(function(item) {
console.log(item.textContent);
});
// "Apple" "Orange" "Grape"
Overview
document.querySelectorAll() is a method that retrieves all HTML elements matching a condition as a NodeList. While document.querySelector() returns only the first match, this method returns all matching HTML elements.
The returned NodeList is an array-like object that supports the length property and index-based access. You can also iterate over it using the forEach() method.
Note that the NodeList is a snapshot taken at the time of the call and will not automatically reflect HTML elements added to the DOM afterward. To get the latest state, you need to call document.querySelectorAll() again.
document.querySelectorAll() is covered in more detail in the tutorial article querySelector() — Selecting Elements with CSS Selectors. Feel free to check it out.
Browser Compatibility
2.5 or earlier ×
3 or earlier ×
8 or earlier ×
9 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.