-1

What is the most correct solution between:

var html="<div>";
for(...){
   html +="asdfgh";
}
html+="</div>";
document.getElementById('test').innerHTML= html;

and:

document.getElementById('test').innerHTML="<div>";
for(...){
   document.getElementById('test').innerHTML +="asdfgh";
}
document.getElementById('test').innerHTML +="</div>";
user2992868
  • 157
  • 1
  • 1
  • 5
  • #2 is worse than #1, since each time the innerHTML is updated, the layout needs to be recalculated. – enhzflep Nov 21 '13 at 17:30
  • I think the first approach is better as test node object is referenced only once and it will be faster. Furthermore it also depends upon the situation if there is a lot of html in string then I think it will be better to write html to dom node when the size of string reaches a certain length. – asim-ishaq Nov 21 '13 at 17:30
  • possible duplicate of [Appending HTML string to the DOM](http://stackoverflow.com/questions/7327056/appending-html-string-to-the-dom) – Alohci Nov 21 '13 at 17:31

3 Answers3

0

The first solution is better since you don't have to find the element every iteration & update the layout. http://jsperf.com/innerhtmlvsstring

0

I like the first one better, because you're only accessing the dom once to add your new element and its content. There are obviously a bunch of other ways to do it.

revdrjrr
  • 1,025
  • 1
  • 8
  • 16
0

Following is a bit faster:
Don't do string manipulation inside for loop*

var html;
html.push ( "<div>" );
for(...){
   // html +="asdfgh";  Inside for loop manipualting String is heavy.
   html.push ( "asdfgh" );
}
html.push ( "</div>" );
document.getElementById('test').innerHTML= html.join("\n");
Rakesh Juyal
  • 35,919
  • 68
  • 173
  • 214