Count all div elements and add each number inside the range using jQuery

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

And add the value of each div within the range

so if i have 4 divs inside the page like this

<div>first div</div> <div>second div</div> <div>third div</div> 

each div should show its order and be so

 <div>first div <span>1</span></div> <div>second div <span>2</span></div> <div>third div <span>3</span></div> 

This html example code in jsfiddle

http://jsfiddle.net/CtDLe/

I need the result to be the same as using jQuery

http://jsfiddle.net/CtDLe/1/

+4
source share
4 answers

A simple each loop does the trick:

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

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

+10
source
 $("div").each(function(idx,elem) { $("<span>").text(idx).appendTo(wherever); }); 
+1
source

You can try the following:

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

JSFiddle example

+1
source
 var counter = 1; $('h1').each(function () { $(this).find('span').html(counter); counter++; }); 

JsFiddle example

0
source

Source: https://habr.com/ru/post/1497062/


All Articles