0

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.

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.