Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of table rows between two specific rows with jQuery

<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

like image 958
Callum Avatar asked Mar 04 '09 23:03

Callum


People also ask

How can I count the number of rows in a table using jQuery?

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.

How can we count dynamically added table rows in jQuery?

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.

How do I count rows in a table?

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).


3 Answers

This will get you what you want

var childCount = ($('#parent_2').get(0).rowIndex - $('#parent_1').get(0).rowIndex) - 1;
like image 74
Chatu Avatar answered Oct 07 '22 13:10

Chatu


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.

like image 20
Miles Avatar answered Oct 07 '22 14:10

Miles


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;
});
like image 42
Samantha Branham Avatar answered Oct 07 '22 12:10

Samantha Branham