Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery iterate over child elements

Tags:

jquery

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?

like image 539
JD Isaacks Avatar asked Nov 05 '10 19:11

JD Isaacks


People also ask

How do I iterate through a div in jQuery?

jQuery Selector can be used to find (select) HTML elements from the DOM. Once an element is selected, the jQuery children() method is called to find all the child elements of the selected element.

How do I iterate through a Div child?

To iterate over Children of HTML Element in JavaScript, get the reference to this HTML Element, get children of this HTML using using children property, then use for loop to iterate over the children.

What is .each in jQuery?

each() jQuery's each() function is used to loop through each element of the target jQuery object — an object that contains one or more DOM elements, and exposes all jQuery functions. It's very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties.

How do you iterate through an object in jQuery?

The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.


3 Answers

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.

like image 195
SLaks Avatar answered Sep 16 '22 15:09

SLaks


$('#ring-preview img.stone-preview').each(function(idx, itm) {     $(itm).rotate(stones[idx].stone_rotation); }); 
like image 43
Agent_9191 Avatar answered Sep 16 '22 15:09

Agent_9191


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.

like image 33
Nick Craver Avatar answered Sep 18 '22 15:09

Nick Craver