0

The images do not have unique ids nor do they have unique classes. How do I change the src value for each element from the array of images.

<img src="img1.jpg" />
<img src="img2.jpg" />
<img src="img3.jpg" />
<img src="img4.jpg" />
var images = ['img11.jpg', 'img22.jpg','img33.jpg','img44.jpg'];
1
  • 1
    so select them by the tag and loop over them. document.querySelectorAll().forEach() is your friend. Commented Dec 16, 2022 at 20:14

1 Answer 1

3

The second argument of forEach is the index of the current iterated item.

Grab the image elements with querySelectorAll, and then use forEach to iterate over them updating the src attribute of each image with the element at the appropriate index in the array.

const arr = ['img11.jpg', 'img22.jpg','img33.jpg','img44.jpg'];

const images = document.querySelectorAll('img');

images.forEach((image, index) => image.src = arr[index]);
<img src="img1.jpg" />
<img src="img2.jpg" />
<img src="img3.jpg" />
<img src="img4.jpg" />

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.