5

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

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

every div need to show his order and be like this

<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 output to be like this using jQuery

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

Jim
  • 1,430
  • 5
  • 18
  • 41
  • 1
    Have you tried anything yet? – j08691 Aug 14 '13 at 15:14
  • 1
    Keep track of a counter, starting with `1` (like `var counter = 1;`). Iterate over the `
    ` elements by using `$("div").each(function (idx, el) { });`, and inside of there, find the inner `` with `$(el).find("span")`, and set its inner text with `.text(counter++)`. Now try that and come back with problems
    – Ian Aug 14 '13 at 15:16

4 Answers4

10

Simple each loop does the trick:

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

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

tymeJV
  • 103,943
  • 14
  • 161
  • 157
1
$("div").each(function(idx,elem) {
    $("<span>").text(idx).appendTo(wherever);
});
Stephen Thomas
  • 13,843
  • 2
  • 32
  • 53
1

You can try this:

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

JSFiddle example

Amin Abu-Taleb
  • 4,423
  • 6
  • 33
  • 50
0
var counter = 1;
$('h1').each(function () {
    $(this).find('span').html(counter);
    counter++;
});

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272