Skip to content
the poor coder

finding total amount of an html table in javascript per row

Poor Man
Published
Reading time
1 min read

There are a few ways you can calculate the total of an HTML table in Javascript. You can use the built-in `Array.prototype.reduce()` function to iterate through each row and add the values in the columns together to get your total. Using the `Array.prototype.reduce()` function:

Text
const table = document.getElementById('myTable');
const total = Array.from(table.rows).reduce((total, row) => {
  const num = row.querySelectorAll('td')[1].textContent;
  return total += parseInt(num);
}, 0);
console.log(total);

In the example above, `table` is the variable that holds the reference to your table element, and `total` is the variable that stores the total value. The `Array.from` function creates an array from the table rows. We then use `reduce` to iterate through each row and find the value in the second column, which we parse to `int` because it's a string value. We then add it to the total and return it. Another way to calculate the total is to create a for loop to iterate through each row and sum the values. Using a for loop:

Text
const table = document.getElementById('myTable');
let total = 0;
for (let i = 0; i < table.rows.length; i++) {
  let num = table.rows[i].querySelectorAll('td')[1].textContent;
  total += parseInt(num);
}
console.log(total);

In the example above, `table` is the variable that holds the reference to your table element, `total` is the variable that stores the total value and `num` is the variable that holds the number value of the second column per row. We then parse the `num` to `int` because it's a string value, and add it to the total. Both of these methods will give you the same result, but depending on your situation, you may find one way more suitable than the other. I hope this helps!

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC