Reputation: 633
I want to automatically count the number of divs with the class ".item". After that, I want jQuery to output the number in a another div within .item, with the class ".itemnumber". So I want the first div to output "1", the second div to output "2", and so on. I know how to count, but I don't know how to output the number for earch div..
Any help is appreciated!
Upvotes: 0
Views: 776
Reputation: 548
how are you?
There might be a more optimized solution, but try this:
var count = $('div.item').length; //Get all items with class "div", which returns an array... so you just use the "length" to get the total count.
$('div.item').each(function(k,v){ //.each takes a first argument which is a function, and this function takes 2 arguments "k"ey and "v"alue.
//v in this case is the div, so:
$('.itemnumber',v).html('Div #' + String(k+1));
});
Let me know if there's any doubt.
Cheers!
Upvotes: 1
Reputation: 9167
<div class="item">
<div class="itemnumber"></div>
</div>
<div class="item">
<div class="itemnumber"></div>
</div>
If your HTML is like that (at a guess), then there's no reason to count the elements, you'd simple do this:
$.each(".item", function(i, val) {
$(this).find(".itemnumber").text(i)
});
Upvotes: 1