I really dont like writing something like
$('body').append('<div class="foo">foo</div>');
Because i usually end up with a quite messy string.
I prefer doing something like
var $div = $('<div/>').attr({ 'class' : 'foo' }).text('foo');
$('body').append($div);
Someone told me that the last option is a lot slower, performance-wise. So i would like some input from you guys. Is there a difference? Which way do you prefer?
Thanks
The second method is very noticably slower in most web browsers.
Basically the first method can pass the string to .innerHTML and let the web browser do its thing in native code, whereas the second method has to invoke a lot of separate JS methods, each of which in turn calls some native function in the web browser to make an adjustment.
For a small example, such as that shown there is almost no noticable difference – but if you profile adding, say 1000 rows to a table using each method, you will notice a significant difference in time taken – particularly on the slower browsers.
In fact, using the second method with any significant amount of elements on IE 8 or lower tends to lock up the browser for some time.