Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda