views:

226

answers:

2

This, I'm sure is a pretty basic question about JavaScript, so apologies in advance.

I have simple unordered list:

<ul>
   <li><a href="">Item number 1</a></li>
   <li><a href="">Item number 2</a></li>
   <li><a href="">Item number 3</a></li>
   <li><a href="">Item number 4</a></li>
   <li><a href="">Item number 5</a></li>
</ul>

How would I be able to prepend an incremental number to those 5 items, so I get:

<ul>
   <li><span>1</span><a href="">Item number 1</a></li>
   <li><span>2</span><a href="">Item number 2</a></li>
   <li><span>3</span><a href="">Item number 3</a></li>
   <li><span>4</span><a href="">Item number 4</a></li>
   <li><span>5</span><a href="">Item number 5</a></li>
</ul>

The logic behind the increment variable is getting me.

A: 

In steps it'd look like this:

  1. You take all LI items and iterate through all of them by adding span with (lis[index]+1)
  2. Next time you insert a LI element you insert it with span who's text is lis.length+1.
Eimantas
+4  A: 

You can iterate over the elements using $.each, using the index argument on the callback function, then build the span element using the current element, and we prepend it to the li:

$('ul li').each(function (i) {
  $('<span>'+ (i+1) +'</span>').prependTo(this);
  // or $('<span></span>').html(i+1).prependTo(this);
});

Check the above snippet here.

Note that I'm adding one to the index i+1, that's because the indexes are zero-based, also I wrap the addition between parentheses because it is in the middle of a string concatenation.

CMS
Absolutely perfect, thanks CMS!
Keith Donegan
You're welcome Keith!
CMS