I've created a website that has numerous img tags. I was wondering if there is a way to fetch the image urls from a JSON file instead of using the img tags without having to Start from scratch.
<main>
<div><img src="https://image.tmdb.org/t/p/w500/pNrQaH0ATrz9wFrNpwfB1aU4MpK.jpg"/
</div>
<div><img src="https://image.tmdb.org/t/p/w500/mYkTq569KOtjdq5zo9mrEY6ecip.jpg"/></div>
<div><img src="https://image.tmdb.org/t/p/w500/7lyBcpYB0Qt8gYhXYaEZUNlNQAv.jpg"/>
</main>
You can simply use query selectors and the .src attribute of each DOM element to set these.
Here's my example HTML and JSON file:
HTML:
<main>
<img class="image" id="1" />
<img class="image" id="2"/>
<img class="image" id="3"/>
</main>
JSON:
{
looneyTunes: "https://image.tmdb.org/t/p/w500/pNrQaH0ATrz9wFrNpwfB1aU4MpK.jpg",
backDown: "https://image.tmdb.org/t/p/w500/mYkTq569KOtjdq5zo9mrEY6ecip.jpg",
backFuture: "https://image.tmdb.org/t/p/w500/7lyBcpYB0Qt8gYhXYaEZUNlNQAv.jpg"
}
My javascript would look something like this:
const domImages = document.querySelectorAll('.image');
fetch('./images.json')
.then(res => {
if (!res.ok) {
throw new Error("HTTP error " + res.status);
}
return res.json();
})
.then(json => {
for (let i = 0; i < domImages.length; i++) {
const imageId = domImages[i].id;
switch(imageId) {
case '1': domImages[i].src = json.looneyTunes;
break;
case '2': domImages[i].src = json.backDown;
break;
case '3': domImages[i].src = json.backFuture;
break;
}
})
.catch(err => {
console.log(err);
})
})
Breakdown:
The query selector all is finding all DOM elements with the class of "image".
const domImages = document.querySelectorAll('.image');
Then we fetch our JSON file that holds all our images.
fetch('./images.json')
We take the response and get the JSON that's contained
.then(res => {
if (!res.ok) {
throw new Error("HTTP error " + res.status);
}
return res.json();
})
We then create a for loop to check over each of our image DOM elements.
for (let i = 0; i < domImages.length; i++) {
We get the ID of each DOM element to check which image is supposed to be set as the source:
const imageId = domImages[i].id;
After this we use Switch to check which ID this DOM element has. If it's '1', we use the .src attribute to assign the Looney Tunes picture as it's source.
switch(imageId) {
case '1': domImages[i].src = json.looneyTunes;
break;
Then we just repeat for the others and catch any errors we get at the bottom
case '2': domImages[i].src = json.backDown;
break;
case '3': domImages[i].src = json.backFuture;
break;
}
})
.catch(err => {
console.log(err);
})
})
I hope this answers your question. Let me know if you have any issues with it or if this isn't the approach you were going towards.