Mmm. Tough one. :) This should do it, though:
$(function() {
$("tr[id^='parent_']").each(function() {
var count = 0;
$(this).nextAll('tr').each(function() {
if($(this).hasClass('child')) {
count++;
} else {
return false;
}
});
$(this).find('td').append(' (' + count + ')');
});
});
Tested and works.
Although the above works, it is not very efficient. I also want to take a second to suggest you change the format of your HTML a little bit. You want to make your code be as semantically relevant to the content it holds as possible. Having one huge table mixing parents and childs is not the optimal way of achieving this. I am not sure what your use case is here, but consider doing something like this:
<ul>
<li id="parent_1">
<span>Parent 1</span>
<ul>
<li>Children 1</li>
<li>Children 2</li>
<li>Children 3</li>
</ul>
</li>
<li id="parent_2">
<span>Parent 2</span>
<ul>
<li>Children 1</li>
</ul>
</li>
<li id="parent_3">
<span>Parent 3</span>
<ul>
<li>Children 1</li>
<li>Children 2</li>
</ul>
</li>
</ul>
You could still style this however you want to give it the appearance you want, although it may not be as easy if you really are displaying tabular data about the parents and children.
With that code, however, you could then simplify the above with a much more efficient:
$('ul > li').each(function() {
var count = $(this).find('li').length;
$('span', this).append(' (' + count + ')');
});
If changing the code from a table to a list is not possible/desired, but you have access to the server-side code that presumably generates this table, you could at least make things easier then by giving all the children a class with the ID of the parent, and giving all the parents a common class:
<table>
<tr id="parent_1" class="parent">
<td>Parent 1</td>
</tr>
<tr class="child parent-1">
<td>Child 1</td>
</tr>
<tr class="child parent-1">
<td>Child 2</td>
</tr>
<tr id="parent_2" class="parent">
<td>Parent2</td>
</tr>
<tr class="child parent-2">
<td>Child 1</td>
</tr>
<tr id="parent_3" class="parent">
<td>Parent3</td>
</tr>
<tr class="child parent-3">
<td>Child 1</td>
</tr>
<tr class="child parent-3">
<td>Child 2</td>
</tr>
<tr class="child parent-3">
<td>Child 3</td>
</tr>
</table>
Which would then allow you to do this, much faster than the original solution:
$('tr.parent').each(function() {
var id = $(this).attr('id').split('_').pop();
var count = $('tr.parent-' + id).length;
$(this).find('td').append(' (' + count + ')');
});