47

How can I add a class to the first and second td in each tr?

<div class='location'>
<table>
<tbody>
<tr>
<td>THIS ONE</td>
<td>THIS ONE</td>
<td>else</td>
<td>here</td>
</tr>
<tr>
<td>THIS ONE</td>
<td>THIS ONE</td>
<td>else</td>
<td>here</td>
</tr>
</tbody>
</table>
</div>

For the first td, this does nothing?

$(".location table tbody tr td:first-child").addClass("black");

Can I also use second-child?

2

7 Answers 7

116
$(".location table tbody tr td:first-child").addClass("black");
$(".location table tbody tr td:nth-child(2)").addClass("black");

http://jsfiddle.net/68wbx/1/

2
  • I had a table that was into a <form />, not a div and it didn't work.
    – Misi
    Commented May 22, 2013 at 9:07
  • @Misi as long as the <form /> tag has a class of location added, it should work. <form class='location'>...</form>
    – Aaron C
    Commented Dec 10, 2019 at 18:57
22

To select the first and the second cell in each row, you could do this:

$(".location table tbody tr").each(function() {
    $(this).children('td').slice(0, 2).addClass("black");
});
2
  • I like the slice() because it makes it slightly cleaner than James Montagne's solution. Commented Nov 27, 2012 at 16:31
  • I like the one call of this, even though 2 call is simpler looking (voted for both). I keep getting caught by slice(start, end) excludes the "end" one. 0, 2 (just like you have it) means the 1st and the 2nd. (not 1st through 3rd).
    – goodeye
    Commented Jun 26, 2015 at 22:02
10

You can do in this way also

var prop = $('.someProperty').closest('tr');

If the number of tr is in array

$.each(prop , function() {
  var gotTD = $(this).find('td:eq(1)');                 
});
4
$(".location table tbody tr").each(function(){
    $('td:first', this).addClass('black').next().addClass('black');
});

another:

$(".location table tbody tr").find('td:first, td:nth-child(2)').addClass('black');
3

If you want to add a class to the first and second td you can use .each() and slice()

$(".location table tbody tr").each(function(){
    $(this).find("td").slice(0, 2).addClass("black");
});

Example on jsfiddle

1

jquery provides one more function: eq

Select first tr

$(".bootgrid-table tr").eq(0).addClass("black");

Select second tr

$(".bootgrid-table tr").eq(1).addClass("black");

0

You can just pick the next td:

$(".location table tbody tr td:first-child").next("td").addClass("black");
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.