Javascript DOM <table> sum column

Description

Javascript DOM <table> sum column

View in separate window


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Sum Table Column</title>
<script>
  window.onload = function() {//from  w w  w . j  a v a 2s .  com
    let table = document.querySelector("table");
    table.onclick = sum;
  }

  function sum() {
    let rows = document.getElementById("sumtable").getElementsByTagName(
        "tr");
    let sum = 0;

    // start with one to skip first row, which is col headers
    for (let i = 1; i < rows.length; i++) {
      sum += parseFloat(rows[i].childNodes[2].firstChild.data);
    }
    console.log(sum);
  }
</script>

</head>
<body>
  <p>Click on the table to sum the numbers in the third column</p>
  <table id="sumtable">
    <tr>
      <th>Value 1</th>
      <th>Value 2</th>
      <th>Value 3</th>
      <th>Value 4</th>
    </tr>
    <tr>
      <td>--</td>
      <td>**</td>
      <td>5.0</td>
      <td>nn</td>
    </tr>
    <tr>
      <td>18.53</td>
      <td>9.77</td>
      <td>3.00</td>
      <td>153.88</td>
    </tr>
    <tr>
      <td>Alaska</td>
      <td>Montana</td>
      <td>18.33</td>
      <td>Missouri</td>
    </tr>
  </table>
</body>
</html>



PreviousNext

Related