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?
: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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With