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

addEventListener()

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.

The addEventListener() method is a method of the EventTarget interface that allows you to register an event listener on an element or group of elements. It takes three arguments: the event type, the event listener function, and an optional options object.

To use the addEventListener() method with the querySelectorAll() function, you can do the following:

document.querySelectorAll(cssSelector).addEventListener(eventType, eventListener);

Here's an example of how to use this combination to select all the button elements in a document and attach a click event listener to each of them:

document.querySelectorAll('button').addEventListener('click', function(event) { console.log('Button clicked'); });

You can also use the addEventListener() method with a NodeList object obtained through other means, such as by calling the childNodes property of a parent element:

const parentElement = document.querySelector('#parent'); const childNodes = parentElement.childNodes; childNodes.addEventListener('click', function(event) { console.log('Child element clicked'); });

In this example, the addEventListener() method is used to attach a click event listener to all the child nodes of the element with the ID "parent". When any of these child elements is clicked, the event listener function will be called and the message "Child element clicked" will be logged to the console.

Note that the addEventListener() method only works with elements that are capable of generating events, such as button, input, and a elements. If you try to use it with a node that is not an element, or with an element that does not support the specified event type, the method will have no effect.