Reputation: 3172
I have several tables on the same page. I am attempting to write jQuery code that would individually count the rows to each of my tables on the page, and depending whether the # of rows are even or odd, apply different CSS to each individual table.
Using jQuery's .each function, I am able to select each table. But I need a way to count the number of rows in that individual table using the "this" keyword. If there was just one table I could use
var amountOfRows = $(".data tbody tr").length;
But since there are multiple tables I need some code that incorporates the "this" keyword to individually get each row length.
So I am really just wanting to know how to use the "this" keyword to be able to read the # of rows of each of my tables on my page.
Here is a basic jsfiddle: http://jsfiddle.net/49jNn/1/
Here is a simplified version of my HTML code, I have 2-4 a page.
<table class="data">
<thead>
//head row
</thead>
<tfoot>
//footer row
</tfoot>
//I want the number of these rows
<tr>
//multiple <td>
</tr>
<tr>
//multiple <td>
</tr>
<tr>
//multiple <td>
</tr>
</table>
My jQuery code so far, able to loop through the # of tables on a page.
$('table').each(function() {
alert("table");
});
Upvotes: 1
Views: 2425
Reputation: 1187
In your each selector you might want to try something like this,
$('table').each(function(e, table) {
console.log(['Table length', $(table).find('tbody tr').length]);
});
Where e is going to be the index and table is the current table in the each statement.
$(table) will take the javascript object and reference it as a jQuery object which will allow you to use the .find('tbody tr') to get the rows in that table.
Upvotes: 0
Reputation: 144699
You can use $(selector, context)
;
$('tbody tr', this).length;
or find
method:
$(this).find('tbody tr').length;
Upvotes: 3