Ryan
Ryan

Reputation: 1791

Selecting TD inside a table

In jQuery, how to select ALL the TR that only has 2 TD inside? Here's the sample:

<table>
   <tr>
      <td></td>
   </tr>          
   <tr> /* I only want to select this. */
      <td></td>
      <td></td>
   </tr>
   <tr>
      <td></td>
   </tr>
</table>

Upvotes: 2

Views: 2021

Answers (3)

Aventuris
Aventuris

Reputation: 630

Use the length command. I came up with this, you might need to make some slight modifications.

$("table").find("tr").each(function() {
    len = $(this).find("td").length;
    if(len == 2) {
        //do stuff
    }
});

http://api.jquery.com/length/

Upvotes: 0

RightSaidFred
RightSaidFred

Reputation: 11327

For at least two

$('tr > td:nth-child(2)').parent();
  • If there's a td:nth-child(2), then obviously there's at least two tds

For exactly two

$('tr > td:nth-child(2):last-child').parent();
  • If there's a tr > td:nth-child(2):last-child, then the second td is also the last td, so there must be only two.

Or like this:

$('tr').has('td:nth-child(2)');  // at least two

$('tr').has('td:nth-child(2):last-child');  // exactly two

Upvotes: 2

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

You should use the .filter() method to reduce the tr to only those whose children count is 2

$('table tr').filter(function(){
    return $(this).children().length === 2;
});

Demo at http://jsfiddle.net/gaby/xTNcG/

Upvotes: 5

Related Questions