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