开发者

Select all trs from a table with a specific number of tds

I have table

<table>
 <tr>
  <td colspan="3"></td>
 </tr>
 <tr> //select this
  <td></td>
  <td></td>
  <td></td>
 </tr>
 <tr> //select this
   <td></td>
   <td></td>
   <td></td>
 </tr>
</table>

so for the above table i want to select all trs which contains 3 tds

how could i do that with jquery?

basically i would need to get the coun开发者_StackOverflow社区t of such rows.


You can use .filter() [docs]:

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

Notice: @mu's answer is more concise and will perform better in modern browsers. I will still leave this answer as a general demonstration for .filter().


You could select the third <td> in each <tr> and the jump up a level to get the parent:

$('tr td:nth-child(3)').parent();

Using :nth-child in this case is safe because your <tr>s should only have <td> children.

For example:

h = $('<table><tr colspan="3"><td></td></tr><tr id="x"><td><span>x</span></td><td></td><td></td></tr><tr id="y"><td></td><td></td><td></td></tr></table>');
trs = h.find('tr td:nth-child(3)').parent();
// trs[0] is <tr id="x">
// trs[1] is <tr id="y">

And a demo provided by Felix Kling (now that jsfiddle.net is back in action): http://jsfiddle.net/6kMTE


You can use:

$('tr:has(td:eq(2))')

which selects any tr containing a td in position 3 (js is zero-based).

Note your html is invalid - the colspan belongs on the td, not the tr

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜