I want to select td
and th
of a table
. At the moment I only can select td
or th
. How can I make this shorter?
$table.find('tr th:nth-child(' + colIndex + ')').css('color', 'red');
$table.find('tr td:nth-child(' + colIndex + ')').css('color', 'red');
If the TDs contain data you need to not drill too deep, so use an immediate child selector before :nth-child
:
$table.find('tr > :nth-child(' + colIndex + ')').css('color', 'red');
JSFiddle (based on @Rory McCrossan's): http://jsfiddle.net/TrueBlueAussie/o8wwf1ze/1/
You can use multiple selector
var colIndex = 2; var $table = $('table') $table.find('tr').find( 'th:nth-child('+colIndex+'),'+ 'td:nth-child('+colIndex+')') .css('color','red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> </table>
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.