javascripthtmlinnerhtmlanti-patterns

Why is appending to the innerHTML property bad?


I have been told not to append stuff using element.innerHTML += ... like this:

var str = "<div>hello world</div>";
var elm = document.getElementById("targetID");

elm.innerHTML += str; // not a good idea?

What is wrong with it? What other alternatives do I have?


Solution

  • Every time innerHTML is set, the HTML has to be parsed, a DOM constructed, and inserted into the document. This takes time.

    For example, if elm.innerHTML has thousands of divs, tables, lists, images, etc, then calling .innerHTML += ... is going to cause the parser to re-parse all that stuff over again. This could also break references to already constructed DOM elements and cause other chaos. In reality, all you want to do is append a single new element to the end.

    It's better to just call appendChild:

    var newElement = document.createElement('div');
    newElement.innerHTML = '<div>Hello World!</div>';
    elm.appendChild(newElement);​​​​​​​​​​​​​​​​
    

    This way, the existing contents of elm are not parsed again.

    NOTE: It's possible that [some] browsers are smart enough to optimize the += operator and not re-parse the existing contents. I have not researched this.