Button click event does not work in javascript. I have a div with a box id. When I try to assign an onclick to each button, only the last button works properly, the other buttons do not work.
Also, this is a simplified version of my code to explain. I should definitely use innerHTML in the original code. But as long as I’m using innerHTML, the code doesn’t work
also here is my html code:
id = (x) => {
return document.getElementById(x)
};
let box = id('box')
btn = (text, func) => {
var button = document.createElement('button');
button.innerHTML = text;
button.onclick = func;
box.appendChild(button)
}
render = () => {
for (let i = 0; i < 5; i++) {
box.innerHTML += '</br>'
btn('btn ' + i, () => {
console.log(1)
})
}
}
render()
<!-- Project -->
<div id="box"></div>
2
Answers
With
box.innerHTML += '</br>'
you actually do:…which just re-assigns a new HTML string, thereby losing any binding of event handlers.
Instead do the same for the
br
elements as you do for thebutton
elements, and replace the above statement with this:Alternatively, you can maybe just omit the
br
elements, and instead style your buttons to have a "block" style. Like in your CSS you could haveThis assumes those buttons are direct children of some element with id
container
. Adapt as needed for your case.Alternatively, if you really want to keep most of your current code, you can use
.insertAdjacentHTML()
instead of.innerHTML
like this: