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

querySelectorAll() vs querySelector()

The querySelectorAll() function is a method of the Document object in JavaScript that allows you to select a group of elements in a document based on a given CSS selector. It returns a NodeList object, which is a collection of nodes (elements) that can be accessed like an array.

On the other hand, the querySelector() function is also a method of the Document object that allows you to select a single element in a document based on a given CSS selector. It returns a reference to the first element that matches the selector, or null if no such element is found.

The main difference between these two functions is that querySelectorAll() returns a collection of elements, while querySelector() returns a single element. This means that you can use the querySelectorAll() function to select multiple elements at once and perform an action on each of them, while the querySelector() function is more suitable for selecting a single element and working with it directly.

Here's an example of how to use the querySelectorAll() function to select all the p elements in a document and change their text color to red:

document.querySelectorAll('p').forEach(function(element) { element.style.color = 'red'; });

And here's an example of how to use the querySelector() function to select the first p element in a document and change its text color to red:

const firstParagraph = document.querySelector('p'); firstParagraph.style.color = 'red';

Note that the querySelectorAll() function will always return a NodeList object, even if it is empty (i.e., if no elements match the selector). On the other hand, the querySelector() function will return null if no elements match the selector, so you should make sure to check for this value before attempting to access properties or methods of the returned element.