Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

86
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda