I’m trying to renumber my rows, starting with a given start index, after an event. Here’s the HTML for my table:
<table id="table4">
<tr>
<td><span class='col1'>6</span></td>
<td>Score</td>
<td></td>
</tr>
</table>
I add rows in later with jQuery with the same format (the first column cell will always have the <span class='col1'></span> tag).
I’m trying this with a css selector, but its not working (nothing is getting changed):
var startIndex = 6;
$("span .col1").text($(this).closest("tr").index() + startIndex);
Is this the right way to do this? I’m kind of a jQuery noob. If there is a better way to do this, I’m more than happy to consider changing my code structure.
There are two things wrong with your code:
By having a space in your selector
"span .col1"you are getting all elements of any type that have the class “col1” that are descendants of a span element – which in your case is no elements. If you remove the space:"span.col1"that will find all spans that have that class.thisat the point where you used it doesn’t have anything to do with the elements you are selecting, it will be something else though I can’t say what because it depends where the code you’ve shown is (In a function? Global?).Here’s how I’d do it:
Demo: http://jsfiddle.net/sLg7h/1/
(Though I’d probably say
...closest("tr")[0].rowIndexsince that gets the index directly rather than making jQuery figure it out with.index().)The
.text()method accepts a function that will be called for each matching element where the return of the function will become the new text for the current element. More commonly you’d use the parameters of that function to get the old text value and do something to it but in this case of course you just want to set a number so the old value doesn’t matter. Though there was a problem with where you were usingthis, within the callback function passed to.text()jQuery will setthisto the current element.Also you probably don’t really need the span element: you could just have
<td class="col1">and select withtd.col1, but even that isn’t necessary if you use the selector"tr td:first-child"to get the first td in every row…