Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  79] [ 3]  / answers: 1 / hits: 56265  / 12 Years ago, tue, july 17, 2012, 12:00:00

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?


More From » html

 Answers
123

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.


[#84225] Saturday, July 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
larrycodys

Total Points: 394
Total Questions: 93
Total Answers: 78

Location: Romania
Member since Mon, Jun 6, 2022
2 Years ago
;