Search code examples
javascripteventsdom-eventsaddeventlistenerinnerhtml

Losing an event triggering after adding new HTML item


Event triggering is lost after adding new element in container. Example code is below. Event is lost after uncomment last Javascript line

Do you know reason and how resolve this issue?

<div class="container">
  <button class="test-item">text</button>
  <button class="test-item">text</button>
  <button class="test-item">text</button>
  <button class="test-item">text</button>
</div>
var allItems = Array.from(document.querySelectorAll('.test-item'));

allItems.forEach(function(item){
   item.addEventListener('click', function(){
   console.log("Go!");
   });
});

var template = "<button class='test-item'>New button</button>";

//document.querySelector('.container').innerHTML += template;

Solution

  • Rewrite the code which adds a new button to this:

    var template = document.createElement("button");
    template.className = "test-item";
    template.innerHTML = "New Button";
    
    document.querySelector('.container').appendChild(template);
    

    Most likely what happens is when you use += on the inner html of the container it completely recreates the child content. So a complete new set of buttons is created causing any previous event handlers to no longer work.