views:

221

answers:

2

I have a table that looks like:

<table>
   <tr>
      <td>one</td><td>two</td><td>three</td><td>last</td>
   </tr>
   <tr>
      <td>blue</td><td>red</td><td>green</td><td>last</td>
   </tr>
   <tr>
      <td>Monday</td><td>Tuesday</td><td>Wednesday</td><td>last</td>
   </tr>
</table>

What I want is a jquery selector that will choose all but the last td of each table row. I tried:

$("tr td:not(:last)").css("background-color","red");
  //changing color just as a test...

But instead of all cells but the last on each row being changed, all cells but the very last one in the table are selected. Similarly, if I change it to:

$("tr td:last").css("background-color","red");

the only one that changes is the very last cell. How do I choose the last (or not last) of each row?

A: 
$('tr').find('td:not(:last)').css('background-color', 'red');

Translates to: for each element in $('tr') selector, do a find() for all tds that are not last.
New result is about tds now, so you can apply .css() as wanted.

Alex Bagnolini
+2  A: 

Use this:

$('tr td:not(:last-child)').css('background-color', 'red');

It's saying each <td> that's not the last in that particular <tr>

Nick Craver
I'm not sure this will work in my case, but maybe you can tell me for sure. I simplified my html for the sake of the question, but each td has other elements inside, such as inputs and labels. Will the `last-child` look for descendants as well, or just the first-level children?
Anthony
Just the td, since there's no space in the selector means the `:` operators apply to that same element, in this case the `<td>`. So just first-level chidren, if you have a table with nested td's, change the selector to be `tr>td:not(:last-child)`, this ensures only the first child of whatever table/tr you're on.
Nick Craver