Search code examples
jqueryhtml-tablerow

jQuery get table with most rows


I have several tables in my document. How do I get the "id" of the table that has the most table rows?

<table id="1">
  <tr></tr>
  <tr></tr>
</table>

<table id="2">
  <tr></tr>
  <tr></tr>
  <tr></tr>
  <tr></tr>
</table>

<table id="3">
  <tr></tr>
</table>

Solution

  • Off the top of my head, you could try something like this:

    function getLargestTable() {
      var curr=0,max=0, id;
      $('table').each(function(){
        curr = $(this); 
        len = curr.find('tr').length;
        if (len > max) { 
           max=len; 
           id=curr.attr('id');
        }
      });
      return id;
    }       
    

    Probably not the greatest code in the world but it should work;