Tuesday, April 10, 2012

Correct way to find out table row count with jQuery

Yesterday, I got into an interesting problem. There was an HTML table on my page and it was having 20 rows. When I was trying to get the count of no. of rows using .children() method but it was always giving me count as 1. For a while, I was wondering what is happening but after sometime got the reason.

First let me show you what is happening. Let's say there is a HTML table with 3 rows. See the below HTML code.
//Code Starts
<table id='tblData' border='1'>
  <tr>
    <td> Cell 1 </td>
  </tr>
  <tr>
    <td> Cell 2 </td>
  </tr>
  <tr>
    <td> Cell 3 </td>
  </tr>
</table>
//Code Ends
When you use below jQuery code to find out children of table, then it will alert as 1. And don't worry there is nothing wrong with the code.
//Code Starts
$(document).ready(function(){
  alert($('#tblData').children().length);
});
//Code Ends
See result below.



I was wondering that what could be the reason. Why it is giving me count as 1, instead of 3. But I finally find out the reason. If you use the below jQuery code, then you will get the tr(table row) count as 3.
//Code Starts
$(document).ready(function(){
  alert($('#tblData').children().children.length);
});
//Code Ends
Well, the reason is that the way DOM parse the elements. If it doesn't find the <tbody> tag for table, then it adds <tbody> tag to the table and that's why count is returned was 1. But when you use $('#tblData').children().children.length), then you are actually telling jQuery to use path (table > tbody > tr).

See below screenshot of DOM. It's adds tbody tag.


See result below.



The above code works, but it is not efficient. The better way is.
//Code Starts
  var child = $('#tblData tbody').children().length;
//Code Ends
OR
//Code Starts
  var child = $('#tblData tr').length;
//Code Ends
Because in both the codes, we are defining selector efficiently and telling jQuery explicitly to look into specified part of the page, which is much faster.

Feel free to contact me for any help related to jQuery, I will gladly help you.