Home  >  Q&A  >  body text

How do I display a random cat image from an API on my webpage using async-await in JavaScript and HTML?

<p>I'm writing a program that makes calls from an API to get random cat images. I want to be able to display the image on my webpage, not just the url in the console. </p> <p>//This is my html (this is really basic but I just want the output to work)</p> <pre class="brush:php;toolbar:false;"><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Cat Gif</title> </head> <body> <div class="container"> <h1>This is a random image of a cat!</h1> </div> <script src="catGif.js"> </script> </body> </html></pre> <p>//This is my JavaScript</p> <pre class="brush:php;toolbar:false;">let container = document.querySelector(".container"); async function apiFunction() { await fetch("https://api.thecatapi.com/v1/images/search") .then(res => res.json()) .then((result) => { //items = result; let img = document.createElement("img"); img.src = result[0].url; container.appendChild(img); }), (error) => { console.log(error); } }</pre></p>
P粉617237727P粉617237727411 days ago522

reply all(1)I'll reply

  • P粉001206492

    P粉0012064922023-09-05 10:28:01

    You did not call the function you defined.

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Cat Gif</title>
    </head>
    
    <body>
        <div class="container">
            <h1>This is a random image of a cat!</h1>
        </div>
    
        <script>
            let container = document.querySelector(".container");
            async function apiFunction() {
                await fetch("https://api.thecatapi.com/v1/images/search")
                    .then(res => res.json())
                    .then((result) => {
                        //items = result;
                        let img = document.createElement("img");
                        img.src = result[0].url;
                        container.appendChild(img);
                    }),
                    (error) => {
                        console.log(error);
                    }
            }
            // Call the function
            apiFunction();
        </script>
    </body>
    
    </html>

    reply
    0
  • Cancelreply