<table>
<tr id="parent_1">
<td>Parent 1</td>
</tr>
<tr class="child">
<td>Child 1</td>
</tr>
<tr class="child">
<td>Child 2</td>
</tr>
...
<tr id="parent_2">
<td>Parent2</td>
</tr>
...
</table>
How can I find the number of child rows between parent_1 and parent_2 using jQuery?
Edit: Sorry, didn't make it clear that this is just an example, the table could contain any number of parent rows, and any number of child rows
To count the number of rows, the “#Table_Id tr” selector is used. It selects all the <tr> elements in the table. This includes the row that contains the heading of the table. The length property is used on the selected elements to get the number of rows.
Answer: Use the length Property You can simply use the length property to count or find the number of rows in an HTML table using jQuery. This property can be used to get the number of elements in any jQuery object.
Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).
This will get you what you want
var childCount = ($('#parent_2').get(0).rowIndex - $('#parent_1').get(0).rowIndex) - 1;
This:
$('#parent_1 ~ .child:not(#parent_2 ~ *)').size()
Translation: match all elements of class child
that are a sibling of, and come after, #parent_1
, but not those that are a sibling of and come after #parent_2
.
First idea that came to mind. I'm sure there's some elaborate way to select the elements in question, (meaning you would just have to do $(selector).length) but I can't think of one off the top of my head.
var doCount = false;
var numberOfChildren = 0;
$('tr').each(function(i){
if($(this).is("#parent_2"))
doCount = false;
if(count)
numberOfChildren++;
if($(this).is("#parent_1"))
doCount = true;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With