3

in the html : <span class="cart-prize">30.00</span>

const total = [];
const items = document.querySelectorAll('.cart-prize'); //item price displaying on the cart when cart popups


 items.forEach(function(item)
 {               
     total.push(parseFloat(item.textContent)).toFixed(2); 
 });



const totalMoney = total.reduce((accumulator, EachArrayValue) 
  => accumulator + EachArrayValue); 

items.forEach((each) => each = "$"+ each.textContext);

document.getElementById("totalMoney").textContent = 
"$"+totalMoney; //works ok

document.getElementById("itemTotal").textContent = 
total.length + " items"; //works ok

after summing up all the price elements in the total array with the reduce method here I tried to concat "$" string with the each textcontent of "cart-prize":

items.forEach((each) => each = each.textContext + "$");

But not succeed.Only float numbers display on the cart without dollar sign

I couldn't figure out where I've made a mistake. Is there anthing wrong with this method : items.forEach((each) => each = "$" + each.textContext);

2
  • 1
    Why are you trying to overwrite each? Should that not be each.textContext to begin with …? Commented Jan 22, 2019 at 15:07
  • do you refer to the each in the left-hand side of the assignment ? Commented Jan 22, 2019 at 15:13

3 Answers 3

1

you're loosing the reference to the original each object with this override

items.forEach((each) => each = "$"+ each.textContext);

you should try with a standard for loop

for (let i = 0; i < items.length; i++) {
    items[i] = "$"+ items[i].textContext;
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank for you comment but that didn't work either.. element still stays the same without sign
0

The problem using items.forEach((each) => each = each.textContext + "$"); is this only iterates between the items array without create a new one.

Instead of using forEach you could use map, which creates a new array, an assign to the items again like the example bellow:

let items = [{textContent: "example1"}, {textContent: "example2"}];

items = items.map((object) => {
    object.textContent = "$" + object.textContent;
    return object;
});

console.log(items);

For find here more information about the difference between map and foreach.

Comments

0

misorude is correct in his/her comment. All you need to do is use each.textContent instead of each inside of your forEach loop.

items.forEach((each) => each.textContent = "&"+each.textContent);

1 Comment

yes. That was true. Silly but I was sure that I had already tried what he says couple of times before posting here. Only now I realized that I haven't actually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.