How can I assign individual image sources from an array to HTML images using pure ES6?

Using ES6, assign each image element a unique source from an array.

HTML Example:

<img data-index="0">
<img data-index="1">
<img data-index="2">

JavaScript Example:

const imageUrls = ['photoA.jpg', 'photoB.jpg', 'photoC.jpg'];
document.querySelectorAll('img[data-index]').forEach((el, idx) => el.src = imageUrls[idx]);

hey, i tried a similar methd in my blog prject and it worked ok. i just loop thru imgs and assign src from the arr using data-index. make sure your cnts match tho

I have used this approach in a project managing a dynamic photo gallery. The method of associating images to array entries via data attributes has significantly improved code maintainability in my experience. I also incorporated checks to ensure there is a matching array element for each image element, to avoid errors when images might be added or removed dynamically. Wrapping this behavior in a dedicated function further simplified reuse in different parts of the application using pure ES6 code practices.