Take the 2-minute tour ×

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">
        <td><span class='col1'>6</span></td>

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.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

There are two things wrong with your code:

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

  2. this at 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:

var startIndex = 6;
$("span.col1").text(function() {
   return $(this).closest("tr").index() + startIndex;

Demo: http://jsfiddle.net/sLg7h/1/

(Though I'd probably say ...closest("tr")[0].rowIndex since 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 using this, within the callback function passed to .text() jQuery will set this to the current element.

Also you probably don't really need the span element: you could just have <td class="col1"> and select with td.col1, but even that isn't necessary if you use the selector "tr td:first-child" to get the first td in every row...

share|improve this answer
Ahh I see, I didn't consider the change in the scope of this. Thanks for the tip about the space in the selector too, this works perfectly. –  John Leehey Feb 25 '12 at 0:05
Thanks for the edits too, they're really helping me understand. –  John Leehey Feb 25 '12 at 0:07
add comment

Your Answer


