-1

as a newbie in JavaScript. I trying to get the total price of each product.

<div class="product">
  <span class="name">product 1</span>
  <span class="price">25.00</span>
</div>
<div class="product">
  <span class="name">product 2</span>
  <span class="price">45.00</span>  
</div>

<div id="cart-total"></div>

And this is my code... what am i doing wrong?

const products = document.querySelectorAll(".product");
const productName = document.querySelectorAll(".name");
const productPrice = document.querySelectorAll(".price");
const cartTotal = document.querySelector("#cart-total");
let total = 0;

for (i = 0; i < products.length; i++) {
 
  const productPriceValue = parseInt(productPrice[i].innerText);
  total += productPriceValue;
}
console.log(total) // prints 70 where i need it to print 70.00
Refael
  • 145
  • 2
  • 12
  • 1
    `let total` is scoped to a single iteration. See [What is the scope of variables in JavaScript?](/q/500431/4642212). Also, `parseInt` for strings like `25.00` is very likely going to be wrong sooner or later. You want `Number(productPrice[i].textContent)` instead. – Sebastian Simon Jan 12 '22 at 12:10
  • 3
    What makes you think you are doing something wrong? You haven't told us what the difference is between what you expect and what you get. – Quentin Jan 12 '22 at 12:10
  • `45.00` doesn't look like an int. I'd say you need `parseFloat` instead :) – Yury Tarabanko Jan 12 '22 at 12:14
  • I am trying to receive the total of the two products e.g. 25.00+45.00. Can't get it to add up. – Refael Jan 12 '22 at 12:15
  • Simple version is: Array.from(document.querySelectorAll(".price")).reduce((a, v) => a + parseInt(v.innerText), 0); – devzero Jan 12 '22 at 12:23

1 Answers1

1

Besides converting int to float, you need to define total value above the iteration, it becomes 0 on each element.

neiloth
  • 157
  • 1
  • 11