Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
JS, fetch() with forEach

To add into my index.js file I am given: const imgUrl = "https://dog.ceo/api/breeds/image/random/4"

This is paired with the following html in my index.html:

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Intro to AJAX Practice Tasks</title>
    <script src="src/index.js" charset="utf-8"></script>
  </head>
  <body>
    <h1>Dog CEO</h1>

    <div id="dog-image-container">
      <!-- images here -->
    </div>

    <hr>
    <label for="select-breed">Filter Breeds That Start with:</label>
    <select id="breed-dropdown" name="select-breed">
      <option value="a">a</option>
      <option value="b">b</option>
      <option value="c">c</option>
      <option value="d">d</option>
    </select>

    <ul id="dog-breeds">

    </ul>

  </body>
</html>

My requirements:

  1. on page load, fetches the images using the url above
  2. parses the response as JSON
  3. adds image elements to the DOM for each image in the array

My unsuccessful attempt has taken me here:

document.addEventListener('DOMContentLoaded', {
    const imgUrl = "https://dog.ceo/api/breeds/image/random/4"
    const imgElement = document.createElement('img')
    const div = document.getElementById('div')
    return fetch(imgUrl)
    .then(res => res.json())
    .then (.forEach(img) => {
        imgElement.appendChild(div)
    })
})

I know that I am doing many things incorrectly. I cannot figure out how to append to my element using .forEach. Any input is appreciated. I am a student on day six and struggling.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

const imgUrl = "https://dog.ceo/api/breeds/image/random/4"
document.addEventListener('DOMContentLoaded', () => {
    const div = document.getElementById('dog-image-container');
    fetch(imgUrl)
        .then(res => res.json())
        .then(res => {
            res.message.forEach((imgSrc) => {
                const img = document.createElement('img');
                img.src = imgSrc;
                div.appendChild(img);
            })
        });
});
<div id="dog-image-container">
      <!-- images here -->
    </div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!