javascript - Creating nested DIVs - Tips for perfomance -
i need create html output composed of nested divs, when provided array of objects.
at moment using following code, works. example simplistic in production, have many objects , complex html created , initialized.
at moment using 2 loops, 1 opening , 1 closing divs.
i know if suggest me alternative approach, considering performances, example avoiding double loop , 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>'; } (var = 0, len = data.length; < len; i++) { open(data[i]); } (var = 0, len = data.length; < len; i++) { close(data[i]); } alert(html); /* result <div id="a"> <div id="b"> <div id="c"> </div> </div> </div> */ })();
a classical case recursion, think.
function createhtml(data) { var item = data.shift(), div, child; if (item) { div = document.createelement("div"); div.id = item.id; child = createhtml(data, div); if (child) div.appendchild(child); return div; } } createhtml([{ id: 'a' }, { id: 'b' }, { id: 'c' }]);
building html concatenated strings more error-prone using dom methods it, respect malicious or unintentionally broken inputs. therefore prefer dom methods.
which method fastest - that's measure, recommend sacrificing pure speed on correct , resilient code.
Comments
Post a Comment