Question

<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

Was it helpful?

Solution

This will get you what you want

var childCount = ($('#parent_2').get(0).rowIndex - $('#parent_1').get(0).rowIndex) - 1;

OTHER TIPS

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;
});

I think the best way is probably to count manually. It'll be faster because you can break off when you know you've done counting (useful if your table is huge).

var rowid1 = 'parent_1';
var rowid2 = 'parent_2';

var rows = $("#"+rowid1).parent().find('tr');
var count = 0;

for (var i = 0; i < rows.size(); i++) {
    var el = rows.get(i);

    // Done counting
    if (el.id == rowid2) break;

    if (el.id != rowid1) {
        ++count;
    }
}

alert("There are " + count + " rows between");

Some people have some nice answers here, i was already started on mine so ill just add it for extra info.

$(document).ready(function() {
    n = 0;
    var x = new Array(0,0,0);

    $("table tr").each(function(i)
    {
        if($(this).hasClass("child"))
        {
            x[n] += 1;
        }
        else
        {
            n += 1;
        }
    });

    for(var y = 0; y < x.length; y++)
    {
        alert(x[y]);
    }
});

EDIT btw mine does not care how many parents are there, it will just keep counting as long the array is big enough.

Assuming parent_1 and parent_2 are the start and the end rows respectively:

$("#parent_1").siblings().size() - 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top