Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 958
Rich Bennema Avatar asked Apr 29 '11 21:04

Rich Bennema


2 Answers

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

like image 51
Šime Vidas Avatar answered Sep 26 '22 20:09

Šime Vidas


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/

like image 22
Nabil Kadimi Avatar answered Sep 22 '22 20:09

Nabil Kadimi