Elton Jamie
Elton Jamie

Reputation: 584

Loop through an array using each jquery

HTML:

<div id="background_cycler">
    <img class="active" src="" alt=""/>
    <img src="" alt=""   />
    <img src="" alt=""  />
    <img src="" alt=""/>        
</div>

jQuery:

var bgImg = [
'img/bg1.jpg',
'img/bg2.jpg',
'img/bg3.jpg',
'img/bg4.jpg'
];

$("#background_cycler").each(function(index){
    $(this).find('img').attr("src", bgImg[index]);
});

The above code inserted bg1.jpg into all of my images, where is my mistake? I thought I loop through the bgImg array using each()'s index?

Upvotes: 2

Views: 84

Answers (1)

Sadikhasan
Sadikhasan

Reputation: 18600

You have to iterate all images inside background_cycler div like

$("#background_cycler img").each(function(index){
    $(this).attr("src", bgImg[index]);
});

You are using background_cycler id as selector so it is find first image from div but you need all images inside background_cycler div so you need to loop using $("#background_cycler img").each as described above.

Upvotes: 3

Related Questions