The main problem is that you redefine the HTML of adivcompletely every time you iterate. This means that any event handler you had already bound to a child element of adiv is lost the moment you do adviv.innerHTML = .... Although you assign the same HTML plus some new one, you don't assign the event handlers that were previously defined. So they are lost.

Only the event handler you assign at the last iteration is not destroyed in this way.

Solution

A quick solution would be to first loop to create all the HTML, and then do a separate loop to assign the event handlers: