I have an HTML table that is similar to this simplified example:
<table>
<tbody>
<tr><th>Player</th><th>Score</th></tr>
<tr><td>Jack</td><td>7</td></tr>
<tr><td class="parent">Green Team</td><td></td></tr>
<tr><td class="child">Mark</td><td>11</td></tr>
<tr><td class="child">Tom</td><td>5</td></tr>
<tr><td>Steven</td><td>8</td></tr>
<tr><td>Greg</td><td>4</td></tr>
<tr><td class="parent">Blue Team</td><td></td></tr>
<tr><td class="child">Joe</td><td>10</td></tr>
<tr><td class="child">Jill</td><td>12</td></tr>
<tr><td class="child">Rachel</td><td>9</td></tr>
</tbody>
</table>
I am trying to code the necessary jQuery to iterate through all child rows of a parent, sum the scores, and insert the sum to the parent’s score cell. The rows that are not associated with a parent should be skipped/ignored.
After the jQuery code executes, the above table should be transformed into this:
<table>
<tbody>
<tr><th>Player</th><th>Score</th></tr>
<tr><td>Jack</td><td>7</td></tr>
<tr><td class="parent">Green Team</td><td>16</td></tr>
<tr><td class="child">Mark</td><td>11</td></tr>
<tr><td class="child">Tom</td><td>5</td></tr>
<tr><td>Steven</td><td>8</td></tr>
<tr><td>Greg</td><td>4</td></tr>
<tr><td class="parent">Blue Team</td><td>31</td></tr>
<tr><td class="child">Joe</td><td>10</td></tr>
<tr><td class="child">Jill</td><td>12</td></tr>
<tr><td class="child">Rachel</td><td>9</td></tr>
</tbody>
</table>
I’m not sure the best way to solve this. Any ideas?
You can do something like this:
You can give it a try here, this takes each
<tr>that contains<td class="parent">and goes with.nextUntil()until it finds a row without a<td class="child">. For those rows it loops through the second cell (:nth-child(2)) and adds the value to the sum.