最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Count all div elements and add each number inside span using jQuery - Stack Overflow

programmeradmin6浏览0评论

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 (like var 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
Add a ment  | 

4 Answers 4

Reset to default 10

Simple 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

发布评论

评论列表(0)

  1. 暂无评论