I’m trying to determine how to calculate the difference between successive table cells in jQuery. I have a table that looks like this.
<table id ="tbl">
<tr>
<td>5</td>
<td>12</td>
<td>15</td>
<td>17</td>
</tr>
<tr>
<td>3</td>
<td>6</td>
<td>12</td>
<td>13</td>
</tr>
</table>
I’d like to subtract the first td from the second td (12 – 5), the third from the second (15 – 12), the fourth from the third (17 – 15) etc. I need to do this for every row in the table. I’m sure the answer is simple, but I’m stuck. I know I’ll need to loop through each row, but how can I efficiently make this calculation?
$('#tbl tr').each(function(){
// help!
)}
.prev()and:gt()are your friends.Iterate over each
trand look at all thetds with an index of greater than zero (the seoncdtdand on in eachtr). Take thattdand subtract the.prev()tdto get your answer.Here’s how I’d put the results in a div called
results:Try it out with this jsFiddle
To be more sure of things, you can use parseInt like this: