insert element in the dom using javascript or jquery

前端 未结 2 1615
清歌不尽
清歌不尽 2021-01-14 21:34

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

$(\"ul li:eq(0)\").prepend(\"1&l         


        
相关标签:
2条回答
  • 2021-01-14 22:13

    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/

    0 讨论(0)
  • 2021-01-14 22:15

    Or you can do this like this

      $("ul li").prepend( function(index, html){
                   return ("<span>" + (index+1) + "</span>");
       });
    
    0 讨论(0)
提交回复
热议问题