Definition and Usage
The querySelectorAll()
function returns all elements that match the specified CSS selector within the HTML document or a specific element.
Basic Example
<ul>
<li>Pizza</li>
<li>Burger</li>
<li>Pasta</li>
</ul>
const liElements = document.querySelectorAll("li"); // Selects all <li> elements
console.log(liElements); // NodeList(3) [li, li, li]
// Can use the length property since it's array-like
let liElementsLength = liElements.length;
// Access each element through iteration
for (let i = 0; i < liElementsLength; i++) {
console.log(liElements[i].textContent);
}
// Output: "Pizza" "Burger" "Pasta"
Code Explanation
The length
property returns the number of items in a string, array, or array-like object.
Code Explanation
A for
loop is used to repeat a block of code a specific number of times. It works with both arrays and array-like objects.
Code Explanation
The textContent
property gets or sets the text content of an HTML element.
Syntax
// Within the entire HTML document
document.querySelectorAll(selectors)
// Within a specific element
element.querySelectorAll(selectors)
Parameters
selectors |
The selector string used to identify the target element.
Must be a valid CSS selector string. If not specified or invalid, a TypeError will be thrown. |
---|
Return value
Description
The querySelectorAll()
function retrieves all elements that match a given CSS selector within the HTML document or a specific element.
Finding Elements in the Entire Document
To find all <p>
elements across the entire document (i.e., from the Document
object), you can use:
const matches = document.querySelectorAll("p"); // Search across the entire document
Finding Elements Within a Specific Element
To find all <p>
elements within a specific element, use the following approach:
<div class="container">
<p>This is a child element.</p>
</div>
const container = document.querySelector(".container"); // A specific element
const matches = container.querySelectorAll("p"); // Search within the element
/* Equivalent to:
document.querySelectorAll(".container p");
*/
Code Explanation
The querySelector()
function returns the first matching element, whereas querySelectorAll()
returns all matches as a NodeList
.
This example shows that querySelectorAll()
can also be used on specific element objects—not just the entire document.
Iterating Over the Matched Elements
querySelectorAll()
returns a NodeList
, which is an array-like, iterable object.
You can access elements using index notation and retrieve the number of elements with the length
property.
Here's an example that loops through all <li>
elements and performs an action on each:
<ul>
<li>Pizza</li>
<li>Burger</li>
<li>Pasta</li>
</ul>
const liElements = document.querySelectorAll("li"); // Select all <li> elements
console.log(liElements); // NodeList(3) [li, li, li]
/*
* The NodeList is array-like and iterable.
* You can loop through its elements in several ways.
*/
/* Method 1 – using for...of */
for (const li of liElements) {
console.log(li.textContent);
}
// Output: "Pizza" "Burger" "Pasta"
/* Method 2 – using a standard for loop */
for (let i = 0; i < liElements.length; i++) {
console.log(liElements[i].textContent);
}
// Output: "Pizza" "Burger" "Pasta"
/* Method 3 – using forEach() */
liElements.forEach(li => {
console.log(li.textContent);
});
// Output: "Pizza" "Burger" "Pasta"
Code Explanation:
length
returns the number of items in a string, array, or array-like object.for
andfor...of
loops can be used to iterate over array-like or iterable objects.textContent
gets or sets the text content of an element.
The NodeList
returned by querySelectorAll()
is array-like and supports indexing and iteration. However, it's not a real array, so array methods like push()
and pop()
won't work.
Still, since it's an iterable, it supports the forEach()
method, which makes it convenient to work with.
Use Case Examples
Explore how the querySelectorAll()
function works in different situations.
Apply Styles to All Elements with a Specific Class
<p class="highlight">These elements will have their styles changed.</p>
const highlightedElements = document.querySelectorAll(".highlight");
const elementsLength = highlightedElements.length;
for (let i = 0; i < elementsLength; i++) {
highlightedElements[i].style.backgroundColor = "yellow";
highlightedElements[i].style.color = "green";
}
In this example, all elements with the class
name highlight
are selected and their styles are updated.
Log Information About Specific Element Types
<ul id="my-list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
const listItems = document.querySelectorAll("#my-list li");
const itemsLength = listItems.length;
for (let i = 0; i < itemsLength; i++) {
console.log("Item " + (i + 1) + ": " + listItems[i].textContent);
}
In this example, all <li>
elements inside the element with the id
my-list
are selected, and their text content is logged to the console.
Add Event Listeners to a List of Links
<ul id="my-links">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
const linkList = document.querySelectorAll("#my-links a");
const linksLength = linkList.length;
for (let i = 0; i < linksLength; i++) {
linkList[i].addEventListener("click", function(event) {
event.preventDefault();
alert("Link clicked!");
});
}
In this example, all <a>
elements inside the my-links
list are selected. A click event listener is added to each link to display an alert when clicked.
Return an Empty NodeList When No Matches Are Found
<!DOCTYPE html>
<html lang="en">
<head>
<title>querySelectorAll() Example</title>
</head>
<body>
<div id="myElement">This element can be selected.</div>
<script>
const nonExistentElement = document.querySelectorAll("#nonExistentElement");
if (nonExistentElement.length === 0) {
console.log("No matching elements found.");
} else {
console.log("Matching elements found.");
}
</script>
</body>
</html>
In this example, since there is no element with the id
nonExistentElement
, querySelectorAll()
returns an empty NodeList
. The script then checks the length of the list and logs the appropriate message.
NodeList is Static (Not Live) and Does Not Reflect DOM Changes
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>NodeList</title>
</head>
<body>
<ul id="list">
<li>Pizza</li>
<li>Burger</li>
<li>Pasta</li>
</ul>
<p>Number of li elements: <strong id="li-length-val">3</strong></p>
<button type="button" id="addButton">Add New Item</button>
<script src="none-live.js"></script>
</body>
</html>
const liElements = document.querySelectorAll("li");
document.getElementById("addButton").addEventListener("click", () => {
const newLi = document.createElement("li");
newLi.textContent = 'New Item';
document.getElementById("list").appendChild(newLi);
// This length remains unchanged because the NodeList is static
const liElementsLength = liElements.length;
document.getElementById("li-length-val").textContent = liElementsLength;
});
Code Explanation
The getElementById()
function returns the element that matches the specified id
.
- Pizza
- Burger
- Pasta
Number of li elements: 3
Even after a new <li>
is added to the list, the original NodeList
from querySelectorAll()
does not update. It remains static and does not reflect changes to the DOM in real-time.
Specifications
Specification | |
---|---|
querySelectorAll()
|
DOM Standard #ref-for-dom-parentnode-queryselectorall① |
Browser compatibility
Method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
querySelectorAll()
|
1 | 12 | 3.5 | 3.1 |