Suppose I have a table of column product, rate this is the rows in it
<tr>
<td>pepsi</td>
<td>2</td>
</tr>
<tr>
<td>juice</td>
<td>4</td>
</tr>
I want total rate, example:
<tr>
<td>total</td>
<td>6</td>
</tr>
Suppose I have a table of column product, rate this is the rows in it
<tr>
<td>pepsi</td>
<td>2</td>
</tr>
<tr>
<td>juice</td>
<td>4</td>
</tr>
I want total rate, example:
<tr>
<td>total</td>
<td>6</td>
</tr>
Get all last td of the table and get sum by iterating over them. Finally, generate the tr
with the calculated sum.
// variable for storing the sum
var sum = 0;
// get all last td from tr
// convert node list to array
// for old browser use `[].slice.call` instead
Array.from(document.querySelectorAll('tr td:last-child'))
// iterate over the td elements
.forEach(function(e) {
// calculate the sum based on the content
sum += Number(e.textContent) || 0;
})
// create tr element
var tr = document.createElement('tr');
// add first cell for showing text
tr.insertCell(0).textContent = 'total';
// add second column for sowing the calculated sum
tr.insertCell(1).textContent = sum;
// get the table and append the generated tr element
document.querySelector('table tbody,table').appendChild(tr);
<table>
<tr>
<td>pepsi</td>
<td>2</td>
</tr>
<tr>
<td>juice</td>
<td>4</td>
</tr>
</table>
You can get all the rows of table by table.rows
and loop through that to get cells values like below
(function(){
var table = document.getElementById("mytab1");
var sum = 0;
for (var i = 0, row; row = table.rows[i]; i++) {
sum += parseInt(table.rows[i].cells[1].innerHTML)
// cells[1] is hardcoded (Assumed <td>2</td> will always the second cell your row)
}
var tr = document.createElement('tr');
tr.insertCell(0).textContent = 'total';
tr.insertCell(1).textContent = sum;
table.appendChild(tr);
})();
<table id="mytab1">
<tr>
<td>pepsi</td>
<td>2</td>
</tr>
<tr>
<td>juice</td>
<td>4</td>
</tr>
</table>
You can use innerHTML
table = document.getElementById('id_of_your_table');
table.innerHTML = table.innerHTML + '<tr><td>total</td><td>6</td></tr>';