0

When I run this code I get NaN, but it reads the initial lis correctly. Does .each not work correctly on html elements?

function computeTotal() {
  let total = 0;
  $("li").each(() => {
    total += parseInt($(this).text(), 10);
  });

  $("#total").text(`Total: ${total}`);
}

computeTotal();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>10</li>
  <li>50</li>
  <li>10</li>
</ul>
<div id="total"></div>

It should output a simple total of the numbers inside the lis. But calling this.text() on each li does not return the number inside it.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • You're using an arrow function so `this` will be the outer scope, not the `li` element in the loop. Either use the first argument passed to the `each()` handler, which is the Element object in the iteration, or convert the block to an anonymous function – Rory McCrossan Dec 30 '22 at 16:43

0 Answers0