Please tell me how to add my class for the column in the table (all the cells of the selected column) using jQuery?
For example, I need a column №2
<table id = 'mytable'>
<tbody>
<tr><td></td>...<td></td></tr>
...
<tr><td></td>...<td></td></tr>
</tbody>
</table>
$('#mytable td.eq( 1 )').addClass('myclass'); // set class for only one cell :(
I want
<table id = 'mytable'>
<tbody>
<tr><td></td><td class = 'myclass'></td>...<td></td></tr>
...
<tr><td></td><td class = 'myclass'></td>...<td></td></tr>
</tbody>
</table>
You can use CSS :nth-child()
selector to add rules, no need use jquery
#mytable td:nth-child(2) { color: red; }
<table id='mytable'> <tbody> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> </tr> </tbody> </table>
You can use :nth-child() selector:
$('#mytable tr td:nth-child(2)').addClass('myClass');
The nth-child
will allow you to select the desired column by specifying the column number. Also, you need to include JQuery
plugin in your HTML file.
$('#mytable tr td:nth-child(2)').addClass('myClass');
td:nth-child(2) { color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="mytable"> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> <td>Alfreds Futterkiste</td> <td>Maria Anders</td> <td>Germany</td> </tr> <tr> <td>Centro comercial Moctezuma</td> <td>Francisco Chang</td> <td>Mexico</td> </tr> <tr> <td>Ernst Handel</td> <td>Roland Mendel</td> <td>Austria</td> </tr> <tr> <td>Island Trading</td> <td>Helen Bennett</td> <td>UK</td> </tr> <tr> <td>Laughing Bacchus Winecellars</td> <td>Yoshi Tannamuri</td> <td>Canada</td> </tr> <tr> <td>Magazzini Alimentari Riuniti</td> <td>Giovanni Rovelli</td> <td>Italy</td> </tr> </table>
$('#mytable td:nth-of-type(2)').addClass('myclass');
.myclass { color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id='mytable'> <tbody> <tr> <td>first</td> <td>second</td> <td>thirth</td> </tr> <tr> <td>first</td> <td>second</td> <td>thirth</td> </tr> </tbody> </table>
You can also do like this using Jquery... It will work for your code... which selects element td which comes after another td...
$('#mytable tr td~td').addClass('myClass');
for specific selection... use nth child...
$('#mytable tr td:nth-child(2)').addClass('myClass');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.