ikerhurtado.com
You're in
Iker Hurtado's pro blog
Developer | Entrepreneur | Passionate
I'm a software engineer specialized in simulation, graphics and GPU programming. My target platforms nowadays are Linux, Android and the Web client.    

The innerHTML=+ issue

25 Oct 2016   |   iker hurtado  
Share on Twitter Share on Google+ Share on Facebook
The only noticeable issue I suffered building my first vanilla JavaScript SPA (NOMAD/Encyclopedia web client) was the mysterious removal of event handlers of elements inside element being updated through the innerHTML attribute. The cause is quite obvious. Because of that, the purpose of this entry is mainly as a remainder.

This post is exactly about this problem: Manipulating innerHTML removes events – Friendly Bit. The key point here is that the String type is immutable:

Obviously, events on an element cannot be retained if the element is replaced by a completely different string using innerHTML. You basically throw away that part of the DOM and write it new.

Adding using the unary + (“+=”) is just a “shorthand” for reading, adding, and reassigning values.

Modifying innerHTML causes the content to be re-parsed and DOM nodes to be recreated, losing the handlers you have attached.

A very good alternative seems the Element.insertAdjacentHTML() method.

POST A COMMENT: