1

I'm new with jquery and I want to count the existing elements from a table and the html structure is like:

<table summary="">
    <tr>
       <td>
           <table id="myid" some more attributes> <-- i got that id and 
               <tbody>
                   <tr>foo</tr> <---counting
                   <tr>bar</tr> <---counting
               </tbody>
            </table>
         </td>
      </tr>
 </table>
HTML is apex gernerated.

i've tried jquery statements from jQuery: count number of rows in a table an many more sits but nothing worked for me. My not working "solution" is

 $("table[id='myid'] > tbody >tr").length

or

 $('table#myid >tbody:last >tr').length

I'm thankful for any hints and tips

Mario

Community
  • 1
  • 1
Mario
  • 166
  • 3
  • 12

7 Answers7

3

Use $('table#myid tr').length​.

References:

João Silva
  • 89,303
  • 29
  • 152
  • 158
2

try this.

http://jsfiddle.net/L7Nea/1/

JS

$('#myid tbody tr').length); 
manish
  • 497
  • 9
  • 17
1

if you mean inside your specific table

$('#myid tr').length // <-- this gets all tr inside table with id=myid

Or if you really wanted to traverse the dom and be more specific in case theres another table inside that table

$('#myid > tbody > tr').length

Plus you're already using the ID selector so no need to have table#myid

wirey00
  • 33,517
  • 7
  • 54
  • 65
1

What you have is what you should use, just with the right id:

$("table[id='myid'] > tbody > tr").length

or

$("table#myid > tbody > tr").length

Demo: http://jsfiddle.net/Guffa/bbV3Z/

As the id should be unique in the page, you should be able to use just:

$("#myid > tbody > tr").length

The reason for using #myid > tbody > tr instead of just #myid tr is to make sure that you only get the rows in that specific table, and not rows from tables nested inside it. If you don't have any tables nested inside it, you can just use:

$("#myid tr").length
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

You can use $("#table_id tr").length

kgautron
  • 7,915
  • 9
  • 39
  • 60
0

Use var count = $('#myid tr').length;.

Francis
  • 244
  • 1
  • 4
  • 14
0

Think about performances also by takeing the context first :

$('#myid').find('tr')

here's the perfs comparisons : http://jsperf.com/tr-number

greg
  • 81
  • 3
  • I've also added all other answer snippets on this thread for comparison, feel free to look at it... – greg Aug 30 '12 at 14:02