I need to create an HTML output composed of nested DIVs, when provided with an array of objects.
At the moment I am using the following code, it works. This example it is very simplistic as in the production, I have many objects and complex HTML to be created and initialized.
At the moment I am using two loops, one for opening and one for closing DIVs.
I would like to know if you could suggest me also an alternative approach, considering performances, example avoiding the double loop and so on.
(function () {
var html = '';
var data = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];
function open(item) {
html += '<div id="' + item.id + '">';
}
function close(item) {
html += '</div>';
}
for (var i = 0, len = data.length; i < len; i++) {
open(data[i]);
}
for (var i = 0, len = data.length; i < len; i++) {
close(data[i]);
}
alert(html);
/* RESULT
<div id="a">
<div id="b">
<div id="c">
</div>
</div>
</div>
*/
})();