Home > front end >  I am trying to fetch random images of cats from public-apis to my index.html (picture does not load)
I am trying to fetch random images of cats from public-apis to my index.html (picture does not load)

Time:01-08

It seems to kinda work, but it won't load the picture

let element2 = document.getElementById("button3"); 
element2.addEventListener("click", () => {
let cat_result = document.getElementById("cat_result");
fetch('https://aws.random.cat/meow')
.then(res => res.json())
.then(data => {
cat_result.innerHTML = '<img src="${data.file}"/>'
    })

});

CodePudding user response:

HTML

<img src="" id="cat_result"/>

I believe, your html image tag like this. You can use setAttribute instead of innerHTML.

Js

let element2 = document.getElementById("button3"); 
element2.addEventListener("click", () => {
let cat_result = document.getElementById("cat_result");
fetch('https://aws.random.cat/meow')
.then(res => res.json())
.then(data => {
cat_result.setAttribute('src', data.file);
})

Hope, it will works.

CodePudding user response:

Template literals need to have backticks (``) around them. More about them here

let element2 = document.getElementById("button3"); 
element2.addEventListener("click", () => {
let cat_result = document.getElementById("cat_result");
fetch('https://aws.random.cat/meow')
.then(res => res.json())
.then(data => {
cat_result.innerHTML = `<img src="${data.file}"/>`
    })
});
<button id="button3">click</button>
<div id="cat_result"></div>

  •  Tags:  
  • Related