Why is it suggested to avoid .innerHTML?

Sorry for being a JavaScript noob, but can anyone please explain why is it recommended not to use .innerHTML. When we have something that is faster and easier in form of .innerHTML , why shouldn't we use it ?


Solution 1:

innerHTML is a sledgehammer. It will blast away the contents of the selected DOM element and replace them with whatever happens to be assigned at the time. This leads to a number of HTML escaping and validation issues.

More importantly, for pages where a large number of events are bound, using innerHTML to append another element will regenerate DOM elements, which means event bindings can get lost.

There are also some issues regarding memory leaks in older versions of IE when elements are removed from the DOM.


With all of that said, I'm not telling you that you shouldn't be using innerHTML. I use it all the time in jQuery when I use $(selector).html(). Sometimes a sledgehammer is the right tool for the job, and when events are delegated properly it won't matter how much the content is reloaded.