Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class with jQuery for second columns of table

<table>
    <tr><td>aaa</td><td>ccc</td><td>aaa</td><td>aaa</td><td>bbb</td><td>aaa</td><td>aaa</td></tr>
    <tr><td>aaa</td><td>ccc</td><td>aaa</td><td>aaa</td><td>bbb</td><td>aaa</td><td>aaa</td></tr>
    <tr><td>aaa</td><td>ccc</td><td>aaa</td><td>aaa</td><td>bbb</td><td>aaa</td><td>aaa</td></tr>
    <tr><td>aaa</td><td>ccc</td><td>aaa</td><td>aaa</td><td>bbb</td><td>aaa</td><td>aaa</td></tr>
    <tr><td>aaa</td><td>ccc</td><td>aaa</td><td>aaa</td><td>bbb</td><td>aaa</td><td>aaa</td></tr>
</table>

table td {
    background-color: green;
    padding: 5px;
    border: 1px solid blue;
}

.red {
   background-color: red;
}

LIVE: http://jsfiddle.net/zCduV/1/

How can i add class .red with jQuery for second column in this table (in this example this is there where in td is ccc)?

like image 511
Paul Attuck Avatar asked Jan 26 '12 13:01

Paul Attuck


3 Answers

This maybe?

// selects both table header and table data cells from the second column of the table
$('table th:nth-child(2), table td:nth-child(2)').addClass('red');

http://jsfiddle.net/tdTkQ/

like image 156
Deadlykipper Avatar answered Nov 08 '22 16:11

Deadlykipper


By using the jQuery nth-child selector:

$('td:nth-child(2)').addClass('red');

Reference: http://api.jquery.com/nth-child-selector/

like image 33
ghstcode Avatar answered Nov 08 '22 17:11

ghstcode


$('td:nth-child(2)').addClass('red');
like image 35
frm Avatar answered Nov 08 '22 16:11

frm