Rich Bennema
Rich Bennema

Reputation: 10345

jQuery: how to select the last N columns of each row in a table?

I have a table with 6 columns. I want to run a function on the last 3 columns of each row (excluding the header row). I have the following selector that is working:

$('table.listviewtable > tbody > tr:gt(0)').find('td:gt(2)')
    .each(function () { runMyFunction($(this)); });

Is there a way to do this all in one selector (ie, without the intermediate find)?

Update:

I've tried

$('table.listviewtable > tbody > tr:gt(0) td:gt(2)')

and

$('table.listviewtable > tbody > tr:gt(0) > td:gt(2)')

but they did not work. They returned the 4th, 5th, and 6th columns of the 2nd row and all columns of all subsequent rows.

Upvotes: 5

Views: 14399

Answers (5)

Nabil Kadimi
Nabil Kadimi

Reputation: 10424

Rule

A generic rule to get the X last TD of a TR is:

$('#tbl tr td:nth-last-child(-n+X)');

Example

// Example for the last 3 paragraphs in some section:
$('#my_section p:nth-last-child(-n+3)');

// It's exactly the same as:
$('#my_section p:nth-last-child(3-n)');

Demo

<!-- CSS -->
<style>
  td {
    border: solid 1px #999;
    padding: 2px;
  }
</style>

<!-- HTML -->
<p>Last 3 cells made gray using jQuery</p>
<table>
  <tr>
    <td>One</td>
    <td>Two</td>
    <td>Three</td>
    <td>Four</td>
  </tr>
</table>

<!-- JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    $('table tr td:nth-last-child(-n+3)').css('background', '#CCC');
  });
</script>

Thanks

http://css-tricks.com/useful-nth-child-recipies/

Upvotes: 6

Frenchi In LA
Frenchi In LA

Reputation: 3169

how about

$('td:gt(2)', 'table.litviewtable')

of course if you use th in header.

Upvotes: 0

David Thomas
David Thomas

Reputation: 253506

The easiest, and most obvious selector, would be:

$('tr').each(
function(){
    $(this).find('td:gt(2)').css('background-color','#ffa');
});

JS Fiddle.

Edited because I'm an idiot, and overlooked the obvious flaw in the first suggestion. Incidentally, I'm assuming proper mark-up, using th for the heading rows. However you could amend the selector to:

 $('tbody tr')

To work around that, if you're not using th elements.

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 186113

Here you go:

$('table.listviewtable td:nth-child(n+4)')

Live demo: http://jsfiddle.net/simevidas/qJ3tP/1/

(I'm assuming you're using TH elements for the header cells.)

Upvotes: 8

mVChr
mVChr

Reputation: 50215

$('table.listviewtable > tbody > tr td:gt(2)')

Upvotes: 1

Related Questions