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

87
Visualizações
Creating an individual event listener for each new element appended

I'm trying to make a button, class name "originalButton". When I click original button it needs to append a new button to the page. How do I set an event listener for each button, that will give a different output based on the button's position.

For example if I click originalButton 100 times it would have appended 100 new butons. If I click new button number 1 it will console.log "I am button 1". Likewise if I clicked new button number 100 it must console.log "I am button 100"

Here is the code I've attempted, but I just can't seem to get it to work. I don't need to know how to do this without the help of any js frameworks. Any help will be highly appreciated:

const mainButton = document.querySelector('.mainButton');
let i = 1;

mainButton.addEventListener('click', () => {
const newButton = document.createElement('button');
    document.body.append(newButton);
    newButton.addEventListener('click', () => {
        console.log(`I am button ${i}`);
        i= i+1
    })
    
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  1. Use a single callback function (onButtonClick)
  2. While creating the buttons, save the i somewere (eg: dataset)
  3. In the callback, get the ID and log to console

const mainButton = document.querySelector('.mainButton');
let i = 1;

mainButton.addEventListener('click', () => {
    const newButton = document.createElement('button');
    newButton.onclick = onButtonClick;
    newButton.dataset.id = i;
    newButton.innerHTML = '#' + i;
    i++;
    document.body.append(newButton);    
});

const onButtonClick = () => {
    const e = event.target;
    console.log(`I am button ${e.dataset.id}`);
};
<button class='mainButton'>Add Button</button>

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