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?
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.
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.
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.
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.
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
.
$('#ring-preview img.stone-preview').each(function(idx, itm) { $(itm).rotate(stones[idx].stone_rotation); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With