最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin9浏览0评论

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?

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?

Share Improve this question edited May 29, 2014 at 18:56 BoltClock 724k165 gold badges1.4k silver badges1.4k bronze badges asked May 29, 2014 at 18:37 Alagappan RamuAlagappan Ramu 2,3687 gold badges27 silver badges38 bronze badges 3
  • @AlexMorrise That works! Thanks. Can you add it as an answer? – Alagappan Ramu Commented May 29, 2014 at 18:40
  • try $('tr td:last-child') – Gautam Commented May 29, 2014 at 18:40
  • Just added it as an answer. – musicnothing Commented May 29, 2014 at 18:41
Add a ment  | 

2 Answers 2

Reset to default 15

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

发布评论

评论列表(0)

  1. 暂无评论