I am trying to set a src attribute to several images with a loop. I have 8 images and I would like to insert these 8 images into my html. I'am using a for of loop on a array which comes from a JSON files. My JSON seems to be ok, because I can console.log the good values of the attribute source. The values look like this : "images/img1.png". The img1 becomes img2... The problem is that it put images/img8.png to all the images into the console and just one image in the html.
I tried to put querySelectorAll('.image') but it says TypeError: img.setAttribute is not a function
.
I tried to put another loop into the for of loop, but it makes an infinite loop, still with images/img8.png.
Here is my code :
.then(response => response.json())
.then(data => {
let img = document.querySelectorAll('.image')
for (const item of data) {
img.setAttribute('src', item.source)
console.log(img)
}
}).catch(err => console.error("Une erreur est survenue", err))
Here is my array
[
{
"image_name": "Image1",
"image_id": "1",
"source": "images/img1.png"
},
{
"image_name": "Image2",
"image_id": "2",
"source": "images/img2.png"
},
{
"image_name": "Image3",
"image_id": "3",
"source": "images/img3.png"
},
{
"image_name": "Image4",
"image_id": "4",
"source": "images/img4.png"
},
{
"image_name": "Image5",
"image_id": "5",
"source": "images/img5.png"
},
{
"image_name": "Image6",
"image_id": "6",
"source": "images/img6.png"
},
{
"image_name": "Image7",
"image_id": "7",
"source": "images/img7.png"
},
{
"image_name": "Image8",
"image_id": "8",
"source": "images/img8.png"
}
]
Do you have an idea were the error is ? Thank you.