peggy.go peggy.go - 2 months ago 6
HTML Question

Adding table elements using javascript

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>

Answer

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>