I'm looking to get the instance number of a div, e.g. I have 4 instances of the .test
div, and using .length
just generates 4
. But I want to put the instance number in each div, for example the 3rd instance of the .test
div would have a 3
in it and so on.
jsFiddle demo: /
HTML:
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
jQuery:
$(document).ready(function () {
var n = $(".test").length;
$('.test').html(n);
});
If this is at all possible? Any suggestions would be greatly appreciated!
I'm looking to get the instance number of a div, e.g. I have 4 instances of the .test
div, and using .length
just generates 4
. But I want to put the instance number in each div, for example the 3rd instance of the .test
div would have a 3
in it and so on.
jsFiddle demo: http://jsfiddle/neal_fletcher/YrtjF/
HTML:
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
jQuery:
$(document).ready(function () {
var n = $(".test").length;
$('.test').html(n);
});
If this is at all possible? Any suggestions would be greatly appreciated!
Share Improve this question asked Jan 9, 2014 at 17:04 user1374796user1374796 1,58213 gold badges46 silver badges76 bronze badges4 Answers
Reset to default 12Use the version of html() that takes a function as the parameter
$('.test').html(function (i) {
return i + 1
});
Demo: Fiddle
$(document).ready(function () {
var n = 1;
$('.test').each(function() {
$(this).html(n);
n++;
});
});
You can use this
$(document).ready(function () {
$(".test").html(function(i,v){
return i+1;
});
});
DEMO
you can use each method here
$(document).ready(function () {
$(".test").each(function(i){
$(this).html(i +1);
});
});