0

I'm trying to update a ul tag without having to manually update the HTML.

<div>
    <ul class="list">
        <li>JavaScript</li>
        <li>Ruby</li>
        <li>Python</li>
    </ul>
</div>
<script>
    let currentText = document.querySelectorAll('.list  li').innerText;
    console.log(currentText);
    let nextText = currentText + '!';
    document.querySelectorAll('.list > li').innerText = nextText;
</script>
jsnerd
  • 1
  • 5
  • Your 2 querySelectorAll's are different, and you should be able to just select `li` if there's only 1 list. Then you have to loop through the selection. – wazz Aug 31 '21 at 21:43
  • `querySelectorAll` returns an HTML collection. A collection has no innerText – epascarello Aug 31 '21 at 21:43
  • `document.querySelectorAll('.list > li').forEach(function(elem) { console.log(elem.textContent); });` – epascarello Aug 31 '21 at 21:45
  • You should avoid using `forEach` on a HTML collection as it's an array method (there's more to it here: https://medium.com/@larry.sassainsworth/iterating-over-an-html-collection-in-javascript-5071f58fad6b). A `for` loop would be better, otherwise I agree with everything epascarello has said. `querySelectorAll` requires an index i.e. `document.querySelectorAll('.list li')[i].innerText`. Then use a standard `for` loop to increment `i` – srWebDev Aug 31 '21 at 21:51

0 Answers0