Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Select first and second td

Tags:

jquery

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?

like image 236
stef Avatar asked Jul 05 '11 20:07

stef


People also ask

How to get selected row td value in jQuery?

jQuery: code to get TD text value on button click. text() method we get the TD value (table cell value). So our code to get table td text value looks like as written below. $(document). ready(function(){ // code to read selected table row cell data (values).

How can I get second child in jQuery?

grab the second child: $(t). children(). eq(1);


2 Answers

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

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

like image 53
James Montagne Avatar answered Oct 01 '22 06:10

James Montagne


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");
});
like image 41
Felix Kling Avatar answered Oct 01 '22 07:10

Felix Kling