Super Hero Gang SHG
Super Hero Gang SHG

Reputation: 68

How to loop pokemons out from the PokeAPI?

Hi I am in the process of fetching data down from the pokeapi, I can loop them out in the console, but when I send them to the div ID__Pokemon only the last index comes out, what is the best way to loop the pokemon names out in ID__Pokemon ?

let myApp = document.querySelector('#App');

const divPokemon = document.getElementById('ID__Pokemon');

const api_url = 'https://pokeapi.co/api/v2/pokemon/';

const pokemonData = async () => {
    const response = await fetch(api_url);
    const data = await response.json();
  
    for (const item in data.results) {
        let pokemon = data.results[item];+
        console.log(pokemon.name);
        divPokemon.innerHTML = `Pokemon: ${pokemon.name}`;
    }
};

pokemonData();
<!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>Document</title>
        <script src="function.js" defer></script>
    </head>
    <body>
        <div id="App">
            <div id="ID__Pokemon"></div>
        </div>
    </body>
</html>

Upvotes: 0

Views: 360

Answers (1)

Victor bvn
Victor bvn

Reputation: 161

doing divPokemon.innerHTML = `Pokemon: ${pokemon.name}`; replaces the content with each iteration

Here is an edit of your code which adds a new "li" element to your list, filled with the proper text content

let myApp = document.querySelector('#App');

const divPokemon = document.getElementById('ID__Pokemon');

const api_url = 'https://pokeapi.co/api/v2/pokemon/';

const pokemonData = async () => {
    const response = await fetch(api_url);
    const data = await response.json();
  
    for (const item in data.results) {
        let pokemon = data.results[item];
        console.log(pokemon.name);
        let newPokemon = document.createElement("li");
        newPokemon.innerText = `Pokemon: ${pokemon.name}`;
        divPokemon.appendChild(newPokemon);
    }
};

pokemonData();
<!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>Document</title>
        <script src="function.js" defer></script>
    </head>
    <body>
        <div id="App">
            <div id="ID__Pokemon"></div>
        </div>
    </body>
</html>

Upvotes: 2

Related Questions