return elements that match specified CSS selector(s)

How can I modify elements selected by querySelectorAll()?

Answers:

  • When you use querySelectorAll() in JavaScript, it returns a NodeList of all the elements that match the specified CSS selector. The NodeList is a collection of elements that you can loop through or manipulate. However, keep in mind that querySelectorAll() doesn't return a standard array, so you need to work with it a bit differently. Here are some commonly used methods to modify elements selected by querySelectorAll():

    1. Loop Through the NodeList

    You can loop through the NodeList using either a for loop or forEach method to modify each selected element.

    // Select all elements matching the selector
    const elements = document.querySelectorAll('.my-class');
    
    // Loop through each element and modify it
    elements.forEach((element) => {
        element.style.color = 'red'; // Change text color to red
        element.innerHTML = 'New Content'; // Change inner HTML
    });
    

    2. Convert NodeList to Array

    If you prefer using array methods, you can convert the NodeList to an array using Array.from() or the spread operator [...nodeList].

    const elements = document.querySelectorAll('.my-class');
    
    // Convert NodeList to an array
    const elementsArray = Array.from(elements);
    
    // Now use array methods like map or filter
    elementsArray.forEach((element) => {
        element.style.backgroundColor = 'yellow'; // Change background color to yellow
    });
    

    3. Modifying Attributes

    You can modify attributes such as src, href, id, data-* attributes, etc.

    const links = document.querySelectorAll('a');
    
    links.forEach((link) => {
        link.setAttribute('target', '_blank'); // Open links in new tab
    });
    

    4. Adding or Removing Classes

    You can add or remove classes from each element using the classList property.

    const items = document.querySelectorAll('.item');
    
    items.forEach((item) => {
        item.classList.add('active'); // Add 'active' class
        item.classList.remove('inactive'); // Remove 'inactive' class
    });
    

    5. Adding Event Listeners

    You can also add event listeners to each element.

    const buttons = document.querySelectorAll('button');
    
    buttons.forEach((button) => {
        button.addEventListener('click', () => {
            alert('Button clicked!');
        });
    });
    

    Example

    Here’s a complete example where we change the text, style, and class of elements.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Modify Elements</title>
    </head>
    <body>
        <div class="box">Box 1</div>
        <div class="box">Box 2</div>
        <div class="box">Box 3</div>
    
        <script>
            const boxes = document.querySelectorAll('.box');
    
            boxes.forEach((box) => {
                box.style.backgroundColor = 'lightblue'; // Change background color
                box.innerHTML = 'Modified Box'; // Change content
                box.classList.add('modified'); // Add a class
            });
        </script>
    </body>
    </html>
    

    Summary

    You can manipulate elements selected by querySelectorAll() using loops, modify styles, attributes, classes, and event listeners. The key is to correctly loop through the NodeList and apply the desired modifications to each element.

Related Questions: