The `querySelectorAll()` method in JavaScript is used to return a static (non-live) `NodeList` of all elements that match a specified group of CSS selectors within the document.
elementList = document.querySelectorAll(selectors)
NodeList
(not a live collection) of elements matching the specified group of selectors. If no matches are found, an empty NodeList
is returned.const paragraphs = document.querySelectorAll("p");
console.log(paragraphs.length); // Outputs the number of <p> elements in the document
const elements = document.querySelectorAll(".my-class");
elements.forEach(element => {
console.log(element.textContent); // Outputs the text content of each element with class "my-class"
});
const element = document.querySelectorAll("#my-id");
console.log(element[0]); // Outputs the element with the id "my-id"
const items = document.querySelectorAll("div, p.my-class, span");
items.forEach(item => {
console.log(item.tagName); // Outputs the tag name of each matched element
});
NodeList
returned by querySelectorAll()
is not live, meaning it does not update automatically if the document structure changes.querySelector()
method instead.querySelectorAll()
is widely supported across all modern browsers:
Please browse our website for more documentation and examples. If you need help with the querySelectorAll() function, you can also ask a new question.