tags:

views:

61

answers:

2

I have a table like this:

<table id="myTable">
   <tr><td>1sta</td><td>2nd</td></tr>
   <tr><td>1stb</td><td>2nd</td></tr>
   <tr><td>1stc</td><td>2nd</td></tr>
   <tr><td>1std</td><td>2nd</td></tr>
</table>

Using jQuery How do I select the 1st <td> element in each row of "myTable"?

+6  A: 

The first-child selector grabs each td that is the first child of its parent (the tr in this case).

$('#myTable td:first-child');

http://api.jquery.com/first-child-selector/

patrick dw
Got it. Thank you. I'll mark this as the correct answer when it lets me.
@user - You're welcome. :o)
patrick dw
+1: for getting it right and suggestion of typo to me.
Sarfraz
@Sarfraz - Thanks for the + . :o)
patrick dw
This will break for if there's a nested table won't it?
blesh
@blesh - Not if the OP wants to select the first `td` elements in the nested table too. There wasn't any nested table in the question. It will also break if the OP changes the ID of the table.
patrick dw
And if immediate children are of concern `$('#myTable > tr > td:first-child');` would specify that relationship..
Dan Heberden
@Dan Herberden - That's actually a little tricky since some (but not all) browsers automatically insert a `tbody` between the `table` and the `tr` elements, so the selector would break in some cases. Getting rid of the first `>` would bring you back to the original issue. I think you would ultimately have to put an ID on the inner table, and use a `:not()` selector to make sure the `td` doesn't descend from that.
patrick dw
+2  A: 

Use this selector '#myTable td:first-child'.

That will select the first td for every tr. Avoid the temptation to use :first instead of :first-child. :first will only select a single element. In this case it would be the first cell of the first row.

http://api.jquery.com/first-child-selector/

gestep