Fetching Data from an Api - Console Repeats

I am having a bit of trouble.

I need to create a website that will display three random Chuck Norris jokes using the following API: . I have to use the following URL to fetch the jokes: .

My HTML is as follows:

<!DOCTYPE html>

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chuck Norris Jokes</title>
    <link rel="stylesheet" href="css/main.css" type="text/css">
</head>

<body>
    <!-- Added a navigation bar to display logo. -->
    <nav class="navigation-bar">
        <img src="images/Logo.png" alt=Logo id="logo" />
    </nav>
    <!-- Created a container so I can set the grid sections. -->
    <div id="container">
        <!-- First container for the heading and the image. -->
        <div>
            <h1>Chuck Norris Jokes</h1>
            <img src="images/chuck.png" alt="Chuck Norris Armed" id="chuckshoot">
        </div>
        <!-- Second section for the text and for the button. -->
        <div id="jokegen">
            <div id="jokeTxt">
            <p id="j1"></p>
            <p id="j2"></p>
            <p id="j3"></p>
        </div>
            <button id="jokeBtn" value="fetch">Click Here For A Chuckle!</button>
        </div>
    </div>

    <script type="text/javascript" src="js/main.js"></script>
</body>

</html>

My Javascript is as follows:

// Created an array for the Chuck Norris jokes.
let joke = [];
// Attached an event handler to the button.
document.getElementById('jokeBtn').addEventListener('click', function () {
    // Fetching the API.
    fetch("")
        // Grabbing the information from the JSON file.
        .then(res => res.json())
        // Fetching the joke from value in JSON.
        .then(function (result) {
            for (let i = 0; i < result.value.length; i++) {
            jokes = result.value[0].joke;
            jokes2 = result.value[1].joke;
            jokes3 = result.value[2].joke;

            console.log(jokes);
            console.log(jokes2);
            console.log(jokes3);
            console.log(typeof joke);
            // Displaying the fetched jokes in HTML.
            document.getElementById("j1").innerHTML = jokes;
            document.getElementById("j2").innerHTML = jokes2;
            document.getElementById("j3").innerHTML = jokes3;
            }
        }),
        // If the above could not be executed and an error should occur.
        error => {
            console.log(error + "");
        };
})

The HTML is showing correctly but in console all three jokes appear even if I call a single joke. Please see the screenshot below:

Thank you in advance for the help.

3

1 Answer

You can simplify the Javascript a little and use a forEach loop on the value property within the response.

The error => {console.log(error + "")} piece is not quite right - that should be within a catch segment - ie .catch( err=>console.log(err) ) or similar

document.getElementById( 'jokeBtn' ).addEventListener('click', ()=>{
  fetch( ' )
    .then( res => res.json() )
    .then( json => {
      if( json.type=='success' ){
        json.value.forEach( ( obj, i )=>{
          let node=document.getElementById( 'j' + ( i + 1 ) );
          if( node )node.innerHTML=obj.joke;
        })
      }
    })
})
<nav class="navigation-bar">
  <img src="images/Logo.png" alt=Logo id="logo" />
</nav>
<div id="container">
  <div>
    <h1>Chuck Norris Jokes</h1>
    <img src="images/chuck.png" alt="Chuck Norris Armed" id="chuckshoot">
  </div>
  <div id="jokegen">
    <div id="jokeTxt">
      <p id="j1"></p>
      <p id="j2"></p>
      <p id="j3"></p>
    </div>
    <button id="jokeBtn" value="fetch">Click Here For A Chuckle!</button>
  </div>
</div>
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest