简体   繁体   中英

insert element in the dom using javascript or jquery

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

$("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?

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/

Or you can do this like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM