skip to Main Content

I was playing with Pokemon’s API and I was able to get the names and sprites of the pokemons but got stuck when trying to fetch the array.

    async function fetchData()
    {
    const pokemonName = document.getElementById("pokemonName").value.toLowerCase();

    const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`);

    const data = await response.json();

    let elementTypes = data.types;
    for(let i = 0; i < elementTypes.length; i++)
        {
            let markup = `<li>${elementTypes[i]}</li>`;

            document.getElementById("pokeTypes").innerHTML = markup;
        }
    }

Pokemon can have multiple types and that’s ‘types’ I want to put it in my DIV, which is ‘pokeTypes’. I can’t seem to throw them into the HTML using a for loop

3

Answers


  1. enter image description here

    If i a not wrong you are getting this data right

    Login or Signup to reply.
  2.     async function fetchData()
        {
        const pokemonName = document.getElementById("pokemonName").value.toLowerCase();
    
        const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`);
    
        const data = await response.json();
    
        let elementTypes = data.types;
        let content = ''
        for(let i = 0; i < elementTypes.length; i++)
            {
                let markup = `<li>${elementTypes[i].type.name}</li>`;
    
                content = content.concat(markup); // or content += markup
            }
        document.getElementById("pokeTypes").innerHTML = content
        }

    Need a variable to store each type through the loop. Then set it to the div with id pokeTypes. Or it will replace that div content while looping.

    Login or Signup to reply.
  3. The JSON response of the Pokémon API typically ends in this way:

    { ...,
    "types":[
      {"slot":1,"type":{"name":"grass","url":"https://pokeapi.co/api/v2/type/12/"}},
      {"slot":2,"type":{"name":"poison","url":"https://pokeapi.co/api/v2/type/4/"}}],"weight":1000
    }
    

    So, in order to list all type names of the selected Pokémon you could do something like

    const sel=document.querySelector("select");
    // get the first 20 Pokémon names and put them as options into the select element:
    fetch("https://pokeapi.co/api/v2/pokemon").then(r=>r.json()).then(p=>{
      sel.innerHTML= p.results.map(r=>`<option>${r.name}</option>`).join("");
      showtypes();
    });
    sel.addEventListener("change",showtypes);
    
    function showtypes(){ 
     fetch(`https://pokeapi.co/api/v2/pokemon/${sel.value}`).then(r=>r.json()).then(data=>
      document.querySelector("ul").innerHTML=data.types.map(t=>`<li>${t.type.name}</li>`).join("")
     )
    }
    <select></select>
    <ul></ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search