querySelectorAll() the best JavaScript function in the world!

How can I combine querySelectorAll() with other DOM manipulation methods to perform actions on the selected elements?

1 answer

  1. You can combine querySelectorAll() with other DOM manipulation methods by first selecting the elements you want to work with using querySelectorAll(), then looping through the NodeList returned by querySelectorAll(), and finally applying the DOM manipulation methods you desire to each element in the loop.

    Here's an example that selects all the paragraphs in a document, sets their color to red, and adds the class "bold" to each p element:

    // Select all p elements using querySelectorAll()
    const paragraphs = document.querySelectorAll('p');

    // Loop through the NodeList of p elements
    for (let i = 0; i < paragraphs.length; i++) {
    // Set the color of the p element to red
    paragraphs[i].style.color = 'red';

    // Add the bold class to the p element

    Alternatively, you can use the forEach method to loop through the NodeList:

    document.querySelectorAll('p').forEach(para => {
    para.style.color = 'red';

Related Questions