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

106
Visualizações
Problem with addEventListener to the button

I am creating a simple random user app that every time that the button is clicked, it will show the new user information, my next button doesn't work, i have no idea what i am doing wrong but i think I'm calling the button even before The DOM loads.

const apiUrl = `https://randomuser.me/api`;
const nextBtn = document.querySelector('button');



async function getUser(){

    const res = await fetch(apiUrl);
    const data = await res.json();
    console.log(data.results[0]);
    let results = data.results[0];
    displayUser(results)
}

function displayUser(results){

const userContainer = document.createElement('div');
userContainer.classList.add('user-container');
userContainer.innerHTML = `

<img src="${results.picture.large}" alt="">
        <div class="title">
            <h3>${results.name.first}</h3>
            <h3>${results.name.last}</h3>
        </div>
        <div class="info">
            <h3>${results.location.street.number + ' ' +results.location.street.name}</h3>
            <h3>${results.phone}</h3> 
            <h3>${results.email}</h3>
        </div>
        <button>Next User</button>
       
`;

document.body.appendChild(userContainer);
}

getUser();

nextBtn.addEventListener('click', getUser);

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to bind the event to the button when you create the button. The code does not keep looking for buttons to be added and add events to it.

function add() {
  const userContainer = document.createElement('div');
  userContainer.classList.add('user-container');
  userContainer.innerHTML = `<button>Add</button>`;
  userContainer.querySelector('button').addEventListener('click', add);
  document.body.append(userContainer);

}
add();

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