Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!