Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 972
Alagappan Ramu Avatar asked May 29 '14 18:05

Alagappan Ramu


Video Answer


2 Answers

: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.

like image 140
musicnothing Avatar answered Sep 20 '22 20:09

musicnothing


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.

like image 43
BoltClock Avatar answered Sep 22 '22 20:09

BoltClock