Reza Reza - 4 months ago 6
Javascript Question

How to increase a number for the same class?

I would like to display an increased number (starting with 1 and ending with 47) for each class called

quiz_image
.

The HTML looks kind of like this:

<div class="quiz_image">
Content here
</div>

<div class="quiz_image">
Content here
</div>

<div class="quiz_image">
Content here
</div>


In order to display the number before the class
quiz_image
, I have tried it like this:

var i = 1;
$('.quiz_image').before(i);
i++;


In my code above the number will not increase, since there is probably a loop needed and I have no idea how to start a loop in this case. I hope somebody can help out on this.

Answer

When you use jQuery to get a selector it will return an array of elements. So you'll want to loop through them. I would suggest with something like the jQuery .each() function, which natively provides you with a 0 based index, you could try something like:

$('.quiz_image').each(function(i){
    $(this).before(i + 1); // add one so we dont start at 0
});