I’m trying to write shorter code using jquery. What is the best way to rewrite this function in jquery.
function searchDone(results) {
var result = null;
var parent = document.getElementById('resultList');
parent.innerHTML = '';
var child = null;
for (var i = 0; i < results.SearchResponse.Image.Results.length; i++) {
result = results.SearchResponse.Image.Results[i];
child = document.createElement('li');
child.className = "resultlistitem";
child.innerHTML = '<a href="' + result.MediaUrl +'"><img src="' +
result.Thumbnail.Url +'" alt="' + result.Title +'" /></a>';
parent.appendChild(child);
}
}
Its a bad idea to continually append to the same element in the DOM in loop. It means that the DOM will get redrawn every single time you append a new element.
Do something like this to append only once:
This creates an array will all the “children” in it. Once the each as looped over all the results it empties out the
#resultListand appends all the children.