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
/
I need the output to be like this using jQuery
/
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/CtDLe/
I need the output to be like this using jQuery
http://jsfiddle/CtDLe/1/
Share Improve this question asked Aug 14, 2013 at 15:12 JimJim 1,4405 gold badges18 silver badges42 bronze badges 2- 1 Have you tried anything yet? – j08691 Commented Aug 14, 2013 at 15:14
-
1
Keep track of a counter, starting with
1
(likevar counter = 1;
). Iterate over the<div>
elements by using$("div").each(function (idx, el) { });
, and inside of there, find the inner<span>
with$(el).find("span")
, and set its inner text with.text(counter++)
. Now try that and e back with problems – Ian Commented Aug 14, 2013 at 15:16
4 Answers
Reset to default 10Simple each
loop does the trick:
$("div").each(function(i) {
$(this).find("span").text(++i);
});
Demo: http://jsfiddle/CtDLe/3/
$("div").each(function(idx,elem) {
$("<span>").text(idx).appendTo(wherever);
});
You can try this:
$("div").each(function(i, elem){
$(elem).append($("<span>"+(i+1)+"</span>"));
});
JSFiddle example
var counter = 1;
$('h1').each(function () {
$(this).find('span').html(counter);
counter++;
});
jsFiddle example