'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
})
})
Solution 1:[1]
- Use a single callback function (
onButtonClick) - While creating the buttons, save the
isomewere (eg: dataset) - 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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 0stone0 |
