2

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?

Sadikhasan
18.6k23 gold badges85 silver badges126 bronze badges
asked Mar 6, 2015 at 10:00
1
  • because you are selecting with id...selector will return first matched element with given id Commented Mar 6, 2015 at 10:04

1 Answer 1

3

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.

answered Mar 6, 2015 at 10:03
Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct answer and should be marked accordingly by @Elton Jamie.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.