16

I would like to select all cells of the first column of a table. Can anyone please tell me the code.

Tried this..

$('.sortable tr:nth-child(1)');    // getting entire row.

3 Answers 3

24

This (fairly verbose) selector should work:

$(".sortable tr > :nth-child(1)")

If you want another column, simply change the index to nth-child to something other than 1.

This will select both td (data) and th (header) cells, btw.

$(".sortable tr > :nth-child(1)")
.css("background-color", "yellow");
<table class="sortable">
  <tr> <th>   A </th> <th>   B </th> <th>   C </th> </tr>
  <tr> <td>   1 </td> <td>   2 </td> <td>   3 </td> </tr>
  <tr> <td>  10 </td> <td>  20 </td> <td>  30 </td> </tr>
  <tr> <td> 100 </td> <td> 200 </td> <td> 300 </td> </tr>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

Considerably more verbose, but here's my solution - a small jQuery-plugin that selects all the cells in a column of a table.
16
$('.sortable td:first-child'); 

4 Comments

mmm.... $('.sortable td:first-child'); would take all first td in class .sortable....
In my opinion, it is a good thing that th cells are not selected, as these are usually treated differently. Also, the OP mentioned nothing about th cells.
@ahmadali shafiee: See answer below (highest votes): $(".sortable tr > :nth-child(3)")
@kgiannakakis thanks. but that was the answer. but I wanted a way to select the third column of the table not just third column.
-1
$('.sortable tr td:first').each(function(){ 
     alert($(this).text());
}); 

1 Comment

I believe this will only select the very first cell of the table. Replacing :first with :first-child should give the expected result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.