Russ Powers Russ Powers - 3 months ago 22
Javascript Question

Jquery Math with an HTML Table

so I have a table that's like the following.



<table>
<tr><th>My Table><th class="total"></th></tr>
<tr><td class="title">title 1</td><td class="value">10%</td></tr>

<tr><td class="title">title 1</td><td class="value">20%</td></tr>

<tr><td class="title">title 1</td><td class="value">30%</td></tr>

<tr><td class="title">title 1</td><td class="value">40%</td></tr>
</table>





I'm wanting to calculate the sum of all td's with the "value" class (which should equal 100). I then want to divide the total of "value" (100) by the number or table rows (4) and then display the new toal (25) in the th class "total". I've tried several methods and can't figure this one out. Any help would be deeply appreciated!

Answer

You can query the cells containing your values using document.querySelectorAll and summing up each cell, calling parseFloat on each cell's innerHTML, then insert the average into the total cell using querySelectorAll again. No jQuery needed.

var valueCells = document.querySelectorAll('.value');
var sum = 0;

for (var i = 0; i < valueCells.length; ++i) {
    sum += parseFloat(valueCells[i].innerHTML);
}

document.querySelectorAll('.total')[0].innerHTML = sum / valueCells.length;
<table>
<tr><th>My Table<th class="total"></th></tr>
<tr><td class="title">title 1</td><td class="value">10%</td></tr>

<tr><td class="title">title 1</td><td class="value">20%</td></tr>

<tr><td class="title">title 1</td><td class="value">30%</td></tr>

<tr><td class="title">title 1</td><td class="value">40%</td></tr>
</table>