Given the minimal code sample below I would expect that each dynamically created button in each table row would produce an alert based on the associated onclick event handler.
class A {
constructor() {
var root = document.getElementById('root');
root.innerHTML =
`
<button id="btn-add">+</button>
<table id="tbl"></table>
`
document.getElementById('btn-add').onclick = () => {
this.add()
}
this.counter = 0
}
add() {
var tbl = document.getElementById('tbl').innerHTML +=
`
<li>
<button id="${this.counter}-btn-rmv">-</button>
</li>
`
document.getElementById(this.counter + '-btn-rmv').onclick = () => {
alert('Click event!')
} //<-- each should have an event handler!
this.counter++
}
}
new A()
<div id="root" />
However only the last button in the last row has a functional event handler and produces an alert. The event handlers on the previously created buttons, for some reason are removed. I'm not sufficiently famillier with javascript to understand what is going wrong here, please let me know.
<div id="root"/>is invalid HTML, browsers will auto–correct but will guess at where to put the closing div tag.