return elements that match specified CSS selector(s)

Can I modify the elements returned by querySelectorAll?

Answers:

  • The querySelectorAll method returns a NodeList of elements that match the specified CSS selectors. While you cannot modify the NodeList itself (it's a read-only list), you can certainly modify the individual elements contained within that NodeList.

    For example, you can loop through each element in the NodeList and change attributes, styles, text content, etc. Here's a simple example:

    // Select all <p> elements
    const paragraphs = document.querySelectorAll('p');
    
    // Loop through the NodeList and modify each <p> element
    paragraphs.forEach((p) => {
        p.style.color = 'blue'; // Change text color to blue
        p.textContent += ' - modified'; // Append text
    });
    

    In this example, each <p> element's text color is changed to blue, and the text " - modified" is appended to the end of its content.

    Remember that while the NodeList is read-only, the individual elements can be manipulated as standard DOM elements.