Hello everyone, I am stuck on the very last step of this code.
I am trying to get the value of all elements with a certain className. (check) And then turn those strings into numbers (check) and then add all of those numbers together (now) then set that number as a state (will do)
var pricevar = document.getElementsByClassName("cartprice");
var i;
let pricearray = [];
for (i = 0; i < pricevar.length; i++) {
pricearray[i] = pricevar[i].textContent;
}
var string = JSON.stringify(pricearray);
string.replace(/"/g); //remove whitespace and ""
//Make them into numbers
for (const element of pricearray) {
let numberarray = parseInt(element);
console.log(numberarray)
}
Right now things are working fine. It is logging the numbers to the console. I am wondering how exactly will I be able to add those numbers together and display the total?
I hope this is a simple solution that I am not seeing. Thank you in advance for your time.
If console.log(numberarray)
is logging the number correctly, then you should be able to create another variable (say number
, for example) and add numberarray
to that variable with each iteration of your for
loop.
Does that help?
Ah sorry I wasn’t being so clear. It is logging the numbers but it is logging them all separately. So when I assigned them to a variable it only gave me the first number instead of all of them added together.
The numberarray is logging like this
14
35
Because with each loop, you are overwriting numberarray
with that specific number.
Let’s try this:
Before (and outside of) for (const element of pricearray) {
loop, establish numberarray
as a variable equaling an empty array.
Then in your loop, take your parseInt(element)
(which is returning the correct numbers, just separately right?) and add the number it returns into your numberarray
. There are a couple of array commands you can use to accomplish this.
1 Like
let numberarray = []
for (const element of pricearray) {
let pricenumbers = parseInt(element);
numberarray.push(pricenumbers)
console.log(numberarray)
}
So this is what I came up with. It seems to work because I get an array of 2 items with the two numbers as I want them. So now I just need to add them together.
Thank you for your help!
Glad I could help! Nice work!
1 Like