By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Sum Table Task in HTML with DOM and JavaScript

+1 vote

Write a JS function that finds the first table in a document and sums the values in the last column. The result is then displayed in an element with ID "sum".

There will be no input/output, your program should instead modify the DOM of the given HTML document.

Sample HTML:

    <tr><td>Beer</td>   <td>2.88</td></tr>
    <tr><td>Fries</td>  <td>2.15</td></tr>
    <tr><td>Burger</td> <td>4.59</td></tr>
    <tr><td>Total:</td> <td id="sum"></td></tr>
<button onclick="sum()">Sum</button>


sum table task with javascript, html and dom

asked in JavaScript category by user john7

1 Answer

0 votes

Here is my solution:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
<table border="1">
        <td id="sum"></td>
<button onclick="sum()">Sum the Numbers from <strong>Cost</strong></button>

    function sum() {
        let rows = document.querySelectorAll("table tr td:last-child");
        let sum = 0;
        for (let i = 0; i < rows.length-1; i++) {
            sum += Number(rows[i].textContent);

        document.getElementById("sum").textContent = sum;



answered by user Jolie Ann