Paul Attuck
Paul Attuck

Reputation: 2269

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)?

Upvotes: 7

Views: 14544

Answers (5)

Awais Qarni
Awais Qarni

Reputation: 18006

Take a look at jQuery nth-child-selector. This is what you are looking for.

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

Upvotes: 2

Deadlykipper
Deadlykipper

Reputation: 878

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/

Upvotes: 13

frm
frm

Reputation: 3486

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

Upvotes: 2

Sameera Thilakasiri
Sameera Thilakasiri

Reputation: 9498

Example of this solution.

Upvotes: 1

ghstcode
ghstcode

Reputation: 2912

By using the jQuery nth-child selector:

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

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

Upvotes: 11

Related Questions