[jquery] jQuery Select first and second td

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?

This question is related to jquery

The answer is


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


$(".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');

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)');                 
});

You can just pick the next td:

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

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");
});

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");