querySelectorAll()

a JavaScript function for selecting elements
  1. Welcome
  2. Examples
    - addEventListener()
    - Buttons
    - Data Attribute
    - document.
    querySelectorAll()

    - forEach()
    - Multiple Classes
    - to array
  3. Errors
    - Failed to execute 'querySelectorAll' on 'document'
  4. Advanced
  5. querySelectorAll() vs querySelector()
  6. Performance
  7. Troubleshooting

Links

  1. allowfullscreen
  2. Questions LLC

document.querySelectorAll()

The document.querySelectorAll() function is a method of the Document object in JavaScript. It allows you to find all elements in the document that match a specified CSS selector. It returns a static (not live) NodeList of elements that match the specified group of selectors.

Here is the syntax for using document.querySelectorAll():

const elementList = document.querySelectorAll(selectors);

elementList: a static NodeList of elements that match the specified group of selectors.
selectors: a string containing one or more CSS selectors separated by commas.

Examples

Here are some examples of how to use document.querySelectorAll():

Example 1: Select all elements with a specific class name

const elementList = document.querySelectorAll('.myClass');

This will return a static NodeList of all elements with the class name "myClass".

Example 2: Select all elements with a specific tag name

const elementList = document.querySelectorAll('div');

This will return a static NodeList of all div elements in the document.

Example 3: Select all elements with a specific attribute

const elementList = document.querySelectorAll('[data-attribute]');

This will return a static NodeList of all elements with a "data-attribute" attribute.

Example 4: Select all elements that match multiple selectors

const elementList = document.querySelectorAll('div.myClass, span.myClass');

This will return a static NodeList of all div elements with the class "myClass" and all span elements with the class "myClass".

You can use any valid CSS selector in the querySelectorAll() function. For more information on CSS selectors, see the W3C documentation.