I populate a list with search results appending li elements. I update DOM for each result.
for (var i = 0; i < topics.length; i++) {
$("#searchResults").append(
$("<li />")
.append(result.Name)
.addClass("example")
);
};
I want to make a group of li elements first and update DOM-tree just once.
I try something like this:
var list = $([]);
for (var i = 0; i < topics.length; i++) {
list.append(
$("<li />")
.append(result.Name)
.addClass("example")
);
};
$("#searchResults").append(list);
But div $("#searchResults") is empty.
Where is the problem?
Something like this should be much faster:
By using a document fragment (
$("<ul />")) and appending to it, then appending at the end, we’re not messing with the entire DOM each append. Also we’re not repeatedly selecting#searchResultseach loop…or checking.lengthwould could also be expensive.Note: this method still uses the DOM to create elements (as opposed to a string), eliminating issues of
result.Namehaving HTML that could screw things up, etc.