tags:

views:

66

answers:

4

I would like to use jQuery to make this:

<ol>
 <li>item a</li>
 <li>item b</li>
</ol>
<ol>
 <li>item c</li>
 <li>item d</li>
 <li>item e</li>
</ol>

…become this:

<ol>
 <li><span>1</span> item a</li>
 <li><span>2</span> item b</li>
</ol>
<ol>
 <li><span>1</span> item c</li>
 <li><span>2</span> item d</li>
 <li><span>3</span> item e</li>
</ol>

(This answer doesn't work for when there are multiple ols on the page; the number would increment across the ols instead of starting from 1 for each individual ol.)

+1  A: 

Probably not the best solution, but it gets the job done :

​$('ol').each(function() {
    $(this).children('li').each(function(i) {
       $(this).prepend(' ' + (i+1) + ' '); 
    });
});​​
Soufiane Hassou
Where are the `<span>` tags? OP may intend to use them for styling.
patrick dw
+2  A: 

You could do something like this (since jQuery 1.4+, .prepend() takes a function):

​$("ol").each(function() {
    $("li", this).prepend(​​​​​​​​function(i) {
        return $("<span />", {text: i+ 1 });
     });
});​

You can see a working demo here

Or, even shorter, but less efficient:

$("ol li").prepend(function() {
   return $("<span />", {text: $(this).index() +1 });
});​

You can see that demo here

Nick Craver
+1, but you need to concatenate in a space character. `(i+1) + ' '` and `($(this).index() +1) + ' '`
patrick dw
@patrick - I agree for the example (actually the space is after the `<span>` in it)...but I'd do this in CSS If I were the OP, more consistent and better than doing it in javascript imo.
Nick Craver
@Nick - Good points. I had the space positioned incorrectly, and I agree that CSS would be a better way to space the appended numbers.
patrick dw
A: 
$("ol").each
(
    function ()
    {
        $("li", this).each
        (
            function (i)
            {
                $(this).prepend("<span>" + (i+1) + "</span>" );
            }
        );
    }
);
BrunoLM
A: 

Or like this:

$('ol > li').each(function() {
    $(this).prepend("<span>" + ($(this).index() +1) + "</span>");
});

Reference: prepend(), index()

Felix Kling