Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

80
Views
Creating JS Array from all Values of html .class

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!