Search code examples
javascriptdomdom-eventsinnerhtml

Why can event listeners stop working after using element.innerHTML?


I am a beginner in JavaScript. A JavaScript book says that one of disadvantages of element.innerHTML is:

Event handlers may no longer work as intended.

I can't understand what this mean. Can someone give me an example?


Solution

  • Most probably, it refers to the technique some people use to insert HTML at the end:

    element.innerHTML += "inserted HTML";
    

    This will get the current HTML, concatenate it with the inserted one, and parse it all.

    As a side effect, all the internal state of the existing elements (like event listeners, checkedness, ...) will be lost.

    var btn = document.querySelector("button");
    btn.addEventListener("click", function() {
      btn.textContent = "I won't work anymore";
      document.body.innerHTML += "<p>Inserted text</p>";
    });
    <button>Click me to insert HTML</button>

    Instead, if you want to insert some HTML at the end of an element, you can use

    element.insertAdjacentHTML('beforeend', "inserted HTML");
    

    This will preserve the existing elements.

    var btn = document.querySelector("button");
    btn.addEventListener("click", function() {
      btn.textContent = "I still work";
      document.body.insertAdjacentHTML("beforeend", "<p>Inserted text</p>");
    });
    <button>Click me to insert HTML</button>

    Another alternative, if you don't mind the inserted content to be wrapped inside an element, is using appendChild:

    var btn = document.querySelector("button");
    btn.addEventListener("click", function() {
      btn.textContent = "I still work";
      var wrapper = document.createElement('div');
      wrapper.innerHTML = "<p>Inserted text</p>";
      document.body.appendChild(wrapper);
    });
    <button>Click me to insert HTML</button>