0
const pokemonAPI = async function (pokemon) {
  const res = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon}`).catch(
    (err) => console.log(err)
  );
  if (res) {
    const data = await res.json();
    renderPokemon(data);
    pokemonArray.push(data);
  }
  return res;
};

// display 20 pokemon
const fetchPokemon = async function () {
  for (let i = 1; i <= 20; i++) {
    await pokemonAPI(i);
    pokemonCounter = i + 1;
  }
};
fetchPokemon();

const renderPokemon = function (data) {
  const html = `
      <div class="col col-container mb-3">
        <div class="card card-size">
         
          <div class="card-body">
            <h3 class="card-title text-center h5">#${data.id} ${data.name}</h3>
            <div class="card-body">
            <ul class="list-group list-group-flush">
              <li class='list-group-item'>Height: ${data.height}</li>
              <li class='list-group-item'>Weight: ${data.weight}</li>
              <li class='list-group-item'>Stats: ${data.stats[0].base_stat}</li>
              <li class='list-group-item'>Stats: ${data.stats[0].effort}</li>
              <li class='list-group-item'>Type: ${data.types[0].type.name}</li>
            </ul>

            <button type="button" class="btn btn-primary btn-favourites" data-id="${data.id}">Favourite</button> 
            </div>
          </div>
        </div>
      </div>
  `;
  pokemonContainer.insertAdjacentHTML('beforeend', html);
};

const addToList = document.querySelector('.btn-favourites');
addToList.addEventListener('click', function (e) {});

I'm getting a null when I try to add an addEventListener to addToList. Probably because it's yet to be rendered, since I have to fetch an API before it renders out the html. So when I try to add an eventListener it's not working and I get an error/null.

Any idea how I can solve this?

Any help would be appreciated! Thanks!

Micke
  • 1
  • 1
  • 1
  • So just use a [`DOMContentLoaded` event listener](//developer.mozilla.org/en/docs/Web/API/Document/DOMContentLoaded_event). _“I have to fetch an API before it renders out the HTML”_ — This sounds extremely dubious. – Sebastian Simon Dec 02 '22 at 22:17

0 Answers0