0

I am trying to gather all text values of my class .amount into one array.

I know I can get the value of the first element with the class .amount using:

const myArray = document.getElementsByClassName('amount')[0].innerHTML;

But I want to get all values of all elements using .amount

My final goal is to build the sum of all values using this code:

function getArraySum(a){
    const total=0;
    for(const i in a) { 
        total += a[i];
    }
    return total;
}

console.log(getArraySum(myArray));

I am very new to JS and also open for other approaches.

Warkus
  • 64
  • 8

1 Answers1

3

My final goal is to build the sum of all values using this code:

Some notes:

  • That code uses for-in, which isn't the correct way to loop through an array or other iterable (it's for looping through object properties). For arrays/iterables, you want for-of. (Not supported in obsolete browsers like IE11.)

  • You don't need an array for this, the result of calling getElementsByClassName("amount") (or querySelectorAll(".amount")) is iterable.

  • You've said "sum" which is a mathematical operation, so you'll need to convert the text you're getting from the DOM to a number. You have lots of options for doing that, I go through them in this answer.

  • I'd use textContent rather than innerHTML, since you probably don't want tag markup.

  • You can't declare total as const, since you're adding to it (modifying its value).

With all that in mind:

function getArraySum(iterable) {
    let total = 0;
    for (const element of iterable) { 
        total += +element.textContent;
    }
    return total;
}

console.log(document.getElementsByClassName("amount));

But if you want to get an array of numbers first, you can do it using Array.from with its mapping callback:

function getArraySum(iterable) {
    let total = 0;
    for (const value of iterable) { 
        total += value;
    }
    return total;
}

const theArray = Array.from(
    document.getElementsByClassName("amount"),
    element => +element.textContent
);
console.log(getArraySum(theArray));

Then

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875