1

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');
1
  • have you find answer? if yes then please select as answer or explain some more.. Commented Apr 14, 2015 at 10:27

2 Answers 2

6

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.