InnerHTML is Evil 3

The usage of innerHTML is most likely the most widely spread non standardized DOM feature available today. It was introcuded in IE4 back in 98. Setting innerHTML parses the string as HTML and replaces the content of the element with the nodes generated by that HTML string. Very useful indeed.

But like most things, innerHTML has an ugly side that will break the most simple functionality. The problem is that when setting it, it will disconnect any previously existing DOM nodes.

var b = document.getElementById("my-button");
document.body.innerHTML += "<p>Add a paragraph?</p>";

So in the example code above, b, is no longer part of the document. It has been disconnected and any code that relies on this has stopped working.

Basically, any time you set innerHTML you have to reinitialize any component that is depending on the DOM nodes you just disconnected.

  • soy

    It’s also worth noting that using x.innerHTML+=”…” or x.innerHTML=x.innerHTML+”…” will cause the entire content within x to be rendered once again, even elements that already rendered. So that’s a VERY bad way to append content. A better way would be to append another child to the element via DOM and innerHTML to that child.

  • http://www.webrawl.com mel

    innerHTML is still one of the best ways to get the job done despite this drawback. All dom programming smells to me . . . looking forward to the day javascript is no more and the html dom as we know it is bye bye

  • Pingback: 核桃博客()