Skip to content Skip to sidebar Skip to footer

Selecting Table Columns (jquery)

I want to give ALL (including ) cells of FIRST and LAST columns some specific classes, I tried this: $('table tr:first-child td:first-child').addClass('first-col-cell');

Solution 1:

EDIT: Your selector was pretty close:

<scripttype="text/javascript">
    $(function() {
        $("table tr td:first-child").text('hello');
        $("table tr td:last-child").text('goodbye');
    });
</script><table><tr><td></td><td></td></tr><tr><td></td><td></td></tr><tr><td></td><td></td></tr></table>

Solution 2:

If th elements matter... not sure how you'd want to treat colspans either.

<!doctype html><table><tr><th></th><td>blah</td><td></td></tr><tr><tdcolspan="2"></td><td></td></tr><tr><td></td><td>blah</td><td></td></tr><tr><td></td><td>blah</td><td></td></tr></table><scripttype="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script><scripttype="text/javascript">
    $(function() {
      $("table tr :first-child").text('first').css('background', 'yellow');
      $("table tr :last-child").text('last').css('background', 'brown');
    });
</script>

Solution 3:

Try breaking it down a little, the traversing you're doing is incorrect

// This will take the first child which is a TD, within any TR in the table.
$("table tr td:first-child").addClass("first-col-cell");

// This will take the first child which is a TR within the table.
$("table tr:first-child").addClass("first-col-cell");

// Just like the above, except now we're doing the last occurances
$("table tr td:last-child").addClass("last-col-cell");
$("table tr:last-child").addClass("last-col-cell");

Then we just need to make sure the mark up is all good

<table>
<tr>
    <td>1</td>
    <td>1</td>
    <td>1</td>
    <td>1</td>
</tr>
<tr>
    <td>2</td>
    <td>2</td>
    <td>2</td>
    <td>2</td>
</tr>
<tr>
    <td>3</td>
    <td>3</td>
    <td>3</td>
    <td>3</td>
</tr>

And then jQuery should go through each one with the following results

<table><trclass="first-col-cell"><tdclass="first-col-cell">1</td><td>1</td><td>1</td><tdclass="last-col-cell">1</td></tr><tr><tdclass="first-col-cell">2</td><td>2</td><td>2</td><tdclass="last-col-cell">2</td></tr><trclass="last-col-cell"><tdclass="first-col-cell">3</td><td>3</td><td>3</td><tdclass="last-col-cell">3</td></tr></table>

Post a Comment for "Selecting Table Columns (jquery)"