JavaScript’s Document.querySelectorAll() method returns a non-live NodeList containing all the elements that match any of the specified CSS selectors.

Syntax

Document.querySelectorAll(parameter);

Parameters

A string containing one or more CSS selectors to match.

Return value

A non-live NodeList containing one Element object for each element that matches any of the selectors or an empty NodeList if no element matches the selectors. Please note that the querySelectorAll() method returns a list of all matching elements, whereas the querySelector() method returns a single matching element.

Exceptions

SyntaxError DOMException

Thrown if the parameter cannot be parsed as a CSS selector list.

Examples

Here are some examples of using the JavaScript querySelectorAll() method.

Suppose we have the following HTML elements:

<div id="welcomeText">
 <p>Welcome to the <a href=”https://javascriptguide.com”>JavaScript Guide</a>!</p>
 <p>You are in the right place if you want to learn JavaScript programming.</p>
</div>

How can we select all the p elements?

We can use the querySelectorAll() method:

let ps = document.querySelectorAll('p');

This selects all the p elements in the document. However, if we only wanted to select all the p elements within the div element, we could use the id of the div element:

let ps = document.querySelectorAll('#welcomeText p');

That is because id attributes are unique identifiers. By using them, we can be sure that we select the right elements. This is how we can iterate over the selected elements and log their textContent to the console:

ps.forEach(p => console.log(p.textContent));
// Welcome to the JavaScript Guide!
// You are in the right place if you want to learn JavaScript programming.

Browser compatibility

Chrome
Edge
Firefox
Internet Explorer
Opera
Safari
Chrome (Android)
Firefox (Android)
Opera (Android)
Safari (iOS)
Samsung Internet
WebView (Android)
querySelectorAll() 1 12 3.5 8 10 3.1 18 4 10.1 2 1.0 4.4

See also