asymptote
asymptote

Reputation: 345

jQuery: Add Numbers into an Ordered List

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

Upvotes: 3

Views: 7931

Answers (4)

Felix Kling
Felix Kling

Reputation: 816930

Or like this:

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

Reference: prepend(), index()

Upvotes: 6

BrunoLM
BrunoLM

Reputation: 100371

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

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630579

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

Upvotes: 3

Soufiane Hassou
Soufiane Hassou

Reputation: 17750

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

​$('ol').each(function() {
    $(this).children('li').each(function(i) {
       $(this).prepend(' ' + (i+1) + ' '); 
    });
});​​

Upvotes: 2

Related Questions