Reputation: 10345
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
Reputation: 10424
A generic rule to get the X last TD of a TR is:
$('#tbl tr td:nth-last-child(-n+X)');
// 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)');
<!-- 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>
http://css-tricks.com/useful-nth-child-recipies/
Upvotes: 6
Reputation: 3169
how about
$('td:gt(2)', 'table.litviewtable')
of course if you use th in header.
Upvotes: 0
Reputation: 253506
The easiest, and most obvious selector, would be:
$('tr').each(
function(){
$(this).find('td:gt(2)').css('background-color','#ffa');
});
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
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