Alagappan Ramu
Alagappan Ramu

Reputation: 2358

jQuery - How to select last column of all rows in a table?

Assuming I have a HTML table as follows (with the appropriate tr, td tags):

a1 | b1 | c1
a2 | b2 | c2
a3 | b3 | c3
a4 | b4 | c4

<table border="1">
<tr>
    <td>a1</td>
    <td>b1</td>
    <td>c1</td>
</tr>
<tr>
    <td>a2</td>
    <td>b2</td>
    <td>c2</td>
</tr>
<tr>
    <td>a3</td>
    <td>b3</td>
    <td>c3</td>
</tr>
<tr>
    <td>a4</td>
    <td>b4</td>
    <td>c4</td>
</tr>
</table>

I'm trying to select all the c* rows to perform an action on them.

Using the $('td:last') selector just selects the last td tag, i.e., c4.

I tried $('tr > td:last') which didn't work. What would be the correct selector in this case?

Upvotes: 6

Views: 18684

Answers (2)

BoltClock
BoltClock

Reputation: 723438

As mentioned, to select every td that is the last child of its parent tr, use :last-child instead:

$('td:last-child')

The reason why the :last selector doesn't work is because it actually gives you the last element in the DOM that matches everything in the selector up to the point where it occurs:

  • $('td:last') returns the last td element
  • $('tr > td:last') returns the last tr > td

Since every td is tr > td by necessity, there is no difference in these two selectors.

Upvotes: 2

musicnothing
musicnothing

Reputation: 3985

:last is a jQuery selector, but it will only select the very last element of that type. You're most likely looking for :last-child.

Similarly, td:first-child will get you the first cell, while :first gets you the first element of that type.

Here's a Fiddle for you to look at with all four examples.

Upvotes: 15

Related Questions