JD Isaacks
JD Isaacks

Reputation: 57974

jquery iterate over child elements

I have a div with the id ring-preview, it has a unspecifed number of img elements with the class stone-preview inside it.

I would like to iterate over each of these child images and call:

$(this).rotate(ring.stones[i].stone_rotation);

Where this refers the img element and i refers to its position within the div.

How can I do that?

Upvotes: 34

Views: 77346

Answers (3)

Nick Craver
Nick Craver

Reputation: 630379

You can use a .each() in these cases, like this:

$("#ring-preview img.stone-preview").each(function(i) {
  $(this).rotate(ring.stones[i].stone_rotation);
});

The first parameter to the callback function is the index you're after.

Upvotes: 8

SLaks
SLaks

Reputation: 887285

You're looking for the .each() method.
For example:

$('.ring-preview').children('img').each(function(i) { 
    $(this).rotate(ring.stones[i].stone_rotation);
});

If the <img> elements aren't direct children, you'll need to call .find instead of .children.

Upvotes: 72

Agent_9191
Agent_9191

Reputation: 7253

$('#ring-preview img.stone-preview').each(function(idx, itm) {
    $(itm).rotate(stones[idx].stone_rotation);
});

Upvotes: 9

Related Questions