0

I want to make all li elements turn to "Hello" when I hit the Test Button but querySelectorAll doesn't do anything, but if I replace with querySelector it works fine for just one element. What am I missing here?

function test() {
    var foundDiv = document.querySelectorAll("li");
    foundDiv.innerText = "Hello";
}
<body>
    <div class="header">
    </div>
    <section id="container">
        <ul>
            <li class="first">one</li>
            <li class="second">two</li>
            <li class="third">three</li>
        </ul>
        <ol>
            <li class="first">one</li>
            <li class="second">two</li>
            <li class="third">three</li>
        </ol>
    </section>
    <div class="footer">
    </div>

    <button onclick="test()"> Test </button>
</body>
Chris
  • 4,762
  • 3
  • 44
  • 79
Ualmeida
  • 3
  • 4

1 Answers1

0

If you look at the documentation for querySelectorAll(), it returns a NodeList, not a single item. From the docs on NodeList: Although NodeList is not an Array, it is possible to iterate over it with forEach(). So, you need to iterate over the results of the query and update each item in the list.

function test() {
    var foundDivs = document.querySelectorAll("li");
    foundDivs.forEach(div => {
      div.innerText = "Hello";
    });
}
<body>
    <div class="header">
    </div>
    <section id="container">
        <ul>
            <li class="first">one</li>
            <li class="second">two</li>
            <li class="third">three</li>
        </ul>
        <ol>
            <li class="first">one</li>
            <li class="second">two</li>
            <li class="third">three</li>
        </ol>
    </section>
    <div class="footer">
    </div>

    <button onclick="test()"> Test </button>
</body>
Chris
  • 4,762
  • 3
  • 44
  • 79