I know there are many topics about this, but they address some variable issue. Mine is much more simple, but it is not working. Only works once.
var bt1;
document.addEventListener('DOMContentLoaded', load);
function load() {
document.body.innerHTML += '<div>welcome</div>';
bt1 = document.getElementById('bt1');
bt1.onclick = clicked;
}
function clicked() {
document.body.innerHTML += '<div>welcome</div>';
}
<body>
<button id="bt1">Click me</button>
</body>
I tried taking the clicked
function in and out of the onclick
statement (as some other topics suggested).
I also tried moving the bt1
variable declaration around (and not using a variable at all).
Another quick fix would be to reattach the listener in clicked mehtod.
Whenever you assign to the
innerHTML
of a container (even if you're just concatenating with existing HTML), the container's contents will be removed, and the newinnerHTML
string will be parsed and then rendered by the browser. So, listeners that used to be attached to anything inside of the container will no longer work.For what you're doing, either use
insertAdjacentHTML
, which will not corrupt listeners, but will perform similar functionality toinnerHTML +=
:Or, explicitly create the new element to append, and use
appendChild
: