Javascript – js/jquery count rows in tbody

javascript, jquery

I am trying to make a simple while loop to count the number of rows in the table #offices, and I have no idea why this isn't working, but the alert keeps returning 0…

html:

<table id="offices" class="table table-striped">    <caption class="text-left">      <p class="lead">Current List of Offices</p>    </caption>    <thead>        <tr>            <th>Office Name</th>            <th>Office abrev.</th>            <th>Display Order</th>            <th>Edit</th>            <!-- TMPL_UNLESS is_agent -->            <th>Delete</th>            <!-- /TMPL_UNLESS -->        </tr>    </thead>    <tbody>    <!-- TMPL_LOOP Office_loop -->    <tr>        <td><!-- TMPL_VAR office_name --></td>        <td><!-- TMPL_VAR short_name --></td>        <td><!-- TMPL_VAR sequence_number ESCAPE=0 --></td>        <td><a href="/office/edit/<!-- TMPL_VAR office_id -->"><i class="fa fa-edit"></i> Edit Office</a></td>        <!-- TMPL_UNLESS is_agent GLOBAL=1 -->        <td><a href="/office/delete/<!-- TMPL_VAR office_id -->"><i class="fa fa-trash-o"></i> Delete Office</a></td>        <!-- /TMPL_UNLESS -->    </tr>    <!-- /TMPL_LOOP -->    </tbody></table>

js/jquery:

var rowCount = $("#offices > tr").length;alert(rowCount);var i = 0;while ( ++i <= rowCount ) {    console.log( "counting rows: " + i );}

Best Solution

Try with this:

$('#tabId tbody').find('tr').length;