Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery selecting all elements except the last per group

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?

like image 243
Anthony Avatar asked Mar 08 '10 12:03

Anthony


People also ask

How to select all <p> elements on a page using jQuery?

The element Selector. The jQuery element selector selects elements based on the element name. You can select all <p> elements on a page like this: $ ( "p" )

How to select all elements based on name in jQuery?

All selectors in jQuery start with the dollar sign and parentheses: $ (). The jQuery element selector selects elements based on the element name. You can select all <p> elements on a page like this:

How to get the best performance using jQuery :selected selector?

In order to get the best performance using :selected, first select elements with a standard jQuery selector, then use.filter (":selected"), or precede the pseudo-selector with a tag name or some other selector.

How to find elements with a specific class in jQuery?

The.class Selector The jQuery.class selector finds elements with a specific class. To find elements with a specific class, write a period character, followed by the name of the class: $ (".test")


1 Answers

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>

like image 129
Nick Craver Avatar answered Sep 23 '22 00:09

Nick Craver