Skip to content
Advertisement

How Do I Programmatically Change The SRC value of the images using JavaScript

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'];

Advertisement

Answer

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" />
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement