return elements that match specified CSS selector(s)

How do I store the elements returned by querySelectorAll in a variable?

Answers:

  • To store the elements returned by querySelectorAll in a variable, you simply assign the result of the method to a variable. The querySelectorAll method returns a NodeList, which is a collection of nodes (elements) that match the specified CSS selector(s).

    Here's a basic example:

    // Use querySelectorAll to select elements
    const elements = document.querySelectorAll('.my-class');
    
    // Now 'elements' holds a NodeList with all elements having the class 'my-class'
    console.log(elements); // Outputs the NodeList to the console
    

    In this example, elements will contain all elements in the document with the class my-class.

    Note

    1. NodeList vs. Array: Remember that the result from querySelectorAll is a NodeList, which is array-like but not an actual array. If you need to use array methods like forEach, map, etc., you can convert it to an array using Array.from or the spread operator:

      // Convert NodeList to Array
      const elementsArray = Array.from(elements);
      // Or using the spread operator
      const elementsArray = [...elements];
      
      // Now you can use array methods
      elementsArray.forEach(element => {
          console.log(element); // Do something with each element
      });
      
    2. Selecting Different Types of Elements: You can adjust the selector in the querySelectorAll method to select different types of elements (e.g., by ID, tag name, etc.).

    That's how you can store elements selected with querySelectorAll in a variable and manipulate them as needed!

Related Questions: