return elements that match specified CSS selector(s)

What operations can I perform on elements returned by querySelectorAll()?

Answers:

  • The querySelectorAll() method in JavaScript returns a static NodeList containing all elements that match a specified CSS selector(s). Since the returned NodeList is not an array, you need to be aware of its specific properties and the types of operations you can perform on it.

    Here are some common operations you can perform on elements returned by querySelectorAll():

    1. Iteration: You can iterate over the NodeList using various methods:

      • Using a for loop:
        const elements = document.querySelectorAll('.class-name');
        for (let i = 0; i < elements.length; i++) {
            console.log(elements[i]);
        }
        
      • Using forEach (you can convert it to an array if needed):
        const elements = document.querySelectorAll('.class-name');
        elements.forEach(element => {
            console.log(element);
        });
        
      • Using the spread operator to convert to an array:
        const elementsArray = [...document.querySelectorAll('.class-name')];
        elementsArray.forEach(element => {
            console.log(element);
        });
        
    2. Accessing Elements: You can access individual elements in the NodeList using indexing:

      const elements = document.querySelectorAll('.class-name');
      const firstElement = elements[0];
      
    3. Manipulating Styles: You can change CSS styles for each element:

      const elements = document.querySelectorAll('.class-name');
      elements.forEach(element => {
          element.style.color = 'red';
      });
      
    4. Adding/Removing Classes: You can add or remove classes:

      const elements = document.querySelectorAll('.class-name');
      elements.forEach(element => {
          element.classList.add('new-class');
      });
      
    5. Setting Attributes: You can set or get attributes:

      const elements = document.querySelectorAll('.class-name');
      elements.forEach(element => {
          element.setAttribute('data-example', 'value');
      });
      
    6. Appending/Removing Child Nodes: You can append or remove child elements:

      const elements = document.querySelectorAll('.class-name');
      elements.forEach(element => {
          const newChild = document.createElement('div');
          element.appendChild(newChild);
      });
      
    7. Event Listeners: You can attach event listeners to each element:

      const elements = document.querySelectorAll('.class-name');
      elements.forEach(element => {
          element.addEventListener('click', () => {
              alert('Element clicked!');
          });
      });
      
    8. Working with Properties: You can manipulate other properties like innerHTML, textContent, etc.:

      const elements = document.querySelectorAll('.class-name');
      elements.forEach(element => {
          element.textContent = 'New Text';
      });
      

    Important Notes

    • The NodeList returned by querySelectorAll() is static, meaning it does not get updated when the DOM changes. If you need a live collection of nodes, use getElementsByClassName() or getElementsByTagName().
    • While NodeList does not have array methods (like .map(), .filter(), etc.), converting it to an array facilitates the use of those methods.

    Overall, querySelectorAll() gives you extensive capabilities for selecting and manipulating multiple DOM elements efficiently.