JavaScript querySelectorAll() Method

You are Here:

JavaScript querySelectorAll() Method

The querySelectorAll() method returns a static NodeList of all the elements that matches a specified CSS selector(s) in the document.

Once the NodeList of matching elements is returned, you can examine it just like any array.

If no matches are found, an empty array is returned.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>P 1</p> <p>P 2</p> <p>P 3</p> <script> var x = document.querySelectorAll("p"); x[0].innerHTML = "Hello there!"; </script> </body> </html>

Syntax

document.querySelectorAll(selectors)

Parameter Values

ValueTypeExplanation
selectorsRequiredSpecifies a DOMString containing one or more selectors to match.
Note: The selector must be a valid CSS syntax, or a SyntaxError exception will occur.

More Examples

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p class="point">P 1</p> <p class="point">P 2</p> <p class="point">P 3</p> <script> var x = document.querySelectorAll(".point"); x[0].innerHTML = "Hello there!"; </script> </body> </html>

Example

Find query length

HTML Online Editor
<!DOCTYPE html> <html> <body> <div> <p class="point">P 1</p> <p class="point">P 2</p> <p class="point">P 3</p> </div> <script> var x = document.querySelectorAll("div > .point"); x[0].innerHTML = "Query Length : " +x.length; </script> </body> </html>

Select

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <div> <h2>Heading</h2> <p>Paragraph</p> </div> <div> <h2>Heading</h2> <p>Paragraph</p> </div> <script> var x = document.querySelectorAll("div > p"); for(var i=0; i<x.length; i++) x[i].style.color = "green"; </script> </body> </html>

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <h2>Heading 2</h2> <p>Paragraph</p> <h3>Heading 3</h3> <p>Paragraph</p> <script> <//Select all h2 and p tags. var x = document.querySelectorAll("h2, p"); for(var i=0; i<x.length; i++) x[i].style.color = "green"; </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author