Reputation: 7577
I want to call a function for every cell in a table except the first column. Until now, I have the following code:
<script type="text/javascript">
$("#resultstable tr").each(function () {
$('td', this).each(function () {
....do my staff...
})
})
</script>
This apply the function to every cell in my table. If I change the code to this, I thought that it will work, but it doesn't.
<script type="text/javascript">
$("#resultstable tr").each(function () {
$('td :not(:first-child)', this).each(function () {
....do my staff...
})
})
</script>
Upvotes: 1
Views: 80
Reputation: 113355
Just slice
the elements:
$("<selector>").slice(1).each(function () {...});
.slice( start [, end ] )
Description: Reduce the set of matched elements to a subset specified by a range of indices.
Another working solution would be to build a spaghetti selector using :not
and :first
:
$("tr").each(function () {
$("td:not(:first)", this).each(function () {
// do something
});
});
var colors = ["#f1c40f", "#2ecc71"];
$("table tr").each(function() {
$("td", this).slice(1).each(function(i) {
$(this).css("background", colors[i])
});
});
setTimeout(function() {
$("table tr").each(function() {
$("td:not(:first)", this).each(function(i) {
$(this).css("background", colors[colors.length - i - 1])
});
});
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<thead>
<tr>
<td>Name</td>
<td>Age</td>
<td>Location</td>
</tr>
</thead>
<tbody>
<tr>
<td>Alice</td>
<td>19</td>
<td>Europe</td>
</tr>
<tr>
<td>Bob</td>
<td>20</td>
<td>Europe</td>
</tr>
<tr>
<td>Carol</td>
<td>15</td>
<td>Australia</td>
</tr>
</tbody>
</table>
Upvotes: 4