2

I am using this script to insert three different span's to the 1st, 2nd and 3rd lis.

$("ul li:eq(0)").prepend("<span>1</span>");
$("ul li:eq(1)").prepend("<span>2</span>");
$("ul li:eq(2)").prepend("<span>3</span>");

Is there a way to refactor this code to remove the redundancy?

2 Answers 2

3

If you want to do it to all li tags that are there:

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

If there are more than three li tags and you only want it done to the first three:

$("ul li:lt(3)").each(function(i) {
    $(this).prepend("<span>" + (i + 1) + "</span>");
});

Working jsFiddle here: http://jsfiddle.net/jfriend00/qhgad/

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

10 Comments

Actually, the second case is the same as the first, except change the selector to $("ul li:lt(3)").
thanks @jfriend I was trying the same thing using for in loop but always end up getting index 0 and when i try to use i+1 it just becomes 01....
It does seem like there's always more to learn on CSS selectors. Thanks for the tip.
@paul - do you understand why the parens are needed around the numbers? You have to get the numbers added together before they are turned into a string because String(1+2) is not the same as String(1) + String(2).
@jfriend yes i understood ...its just i am concatenating 2 strings ...but i used (i+1) too...might be I am doing something wrong
|
1

Or you can do this like this

  $("ul li").prepend( function(index, html){
               return ("<span>" + (index+1) + "</span>");
   });

4 Comments

Cool idea, but that won't add the <span> tags around the content, will it?
it adds span around the number and prepends it to a li content (in the first version I omitted span tag - now added)
+1 @Michal it seems to be working and great trick instead of looping but i don't think u need to pass the html ...
it passes the current html of the element (just in case you want to do something with it). Yes tested and working.

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.