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. Questions
  8. Troubleshooting

External

  1. allowfullscreen
  2. Questions LLC

to array

The querySelectorAll() function is used to select all elements in the document that match a specified CSS selector. It returns a NodeList, which is similar to an array but with some differences in the methods it supports. In order to use array methods like .map() or .forEach() on the results, you will need to convert the NodeList to an actual array.

Here is an example of how to convert the results of querySelectorAll() to an array:

// Select all elements with the class "example" let elements = document.querySelectorAll('.example'); // Convert the NodeList to an array let elementsArray = Array.from(elements); // Use array methods on the elements elementsArray.forEach(function(element) { console.log(element); });

Another way to convert the NodeList to an array is using the spread operator ...

// Select all elements with the class "example" let elements = document.querySelectorAll('.example'); // Convert the NodeList to an array let elementsArray = [...elements]; // Use array methods on the elements elementsArray.forEach(function(element) { console.log(element); });

Another way to convert the NodeList to an array is using the Array.prototype.slice.call(elements)

// Select all elements with the class "example" let elements = document.querySelectorAll('.example'); // Convert the NodeList to an array let elementsArray = Array.prototype.slice.call(elements); // Use array methods on the elements elementsArray.forEach(function(element) { console.log(element); });

In all the above examples, elementsArray is now an array that you can use array methods on.