Count all div elements and add each number inside span using jQuery

前端 未结 4 1618
鱼传尺愫
鱼传尺愫 2021-02-10 02:45

I need to show each number of div in the page in order

And add the value of each div inside span

so if I have 4 divs inside page like this



        
相关标签:
4条回答
  • 2021-02-10 03:01

    You can try this:

    $("div").each(function(i, elem){
     $(elem).append($("<span>"+(i+1)+"</span>"));
    });
    

    JSFiddle example

    0 讨论(0)
  • 2021-02-10 03:05
    $("div").each(function(idx,elem) {
        $("<span>").text(idx).appendTo(wherever);
    });
    
    0 讨论(0)
  • 2021-02-10 03:06
    var counter = 1;
    $('h1').each(function () {
        $(this).find('span').html(counter);
        counter++;
    });
    

    jsFiddle example

    0 讨论(0)
  • 2021-02-10 03:11

    Simple each loop does the trick:

    $("div").each(function(i) {
        $(this).find("span").text(++i);
    });
    

    Demo: http://jsfiddle.net/CtDLe/3/

    0 讨论(0)
提交回复
热议问题