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

Buttons

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

Here's an example of how you might use querySelectorAll() to find all buttons on a webpage:

// Find all buttons on the page const buttons = document.querySelectorAll('button'); // Log the number of buttons found console.log(`Found ${buttons.length} buttons.`); // Loop through the buttons and add a click event listener to each one buttons.forEach(button => { button.addEventListener('click', event => { console.log(`Button clicked: ${event.target.textContent}`); }); });

In this example, querySelectorAll('button') searches the document for all elements that match the CSS selector 'button', which selects all <button> elements. The querySelectorAll() function returns a NodeList of all matching elements, which we store in the buttons constant. We then use the forEach() method to loop through the NodeList and add a click event listener to each button. When a button is clicked, the event listener logs the text content of the button to the console.

You can use any valid CSS selector with querySelectorAll(), not just 'button'. For example, you could use '#some-id' to find an element with the ID 'some-id', or '.some-class' to find all elements with the class 'some-class'.

Here's a more complete example that demonstrates how you might use querySelectorAll() to add a click event listener to all buttons on a webpage:

<!DOCTYPE html> <html> <head> <title>Button Test</title> </head> <body> <button>Button 1</button> <button>Button 2</button> <button>Button 3</button> <script> // Find all buttons on the page const buttons = document.querySelectorAll('button'); // Loop through the buttons and add a click event listener to each one buttons.forEach(button => { button.addEventListener('click', event => { console.log(`Button clicked: ${event.target.textContent}`); }); }); </script> </body> </html>

When you open this HTML file in a web browser and click on one of the buttons, the text content of the button (e.g., "Button 1") will be logged to the console.