Iterating and DOM manipulation
by Ryan Morris
HTML
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<ul class="approach-one">
</ul>
<ul class="approach-two">
</ul>
<ul class="approach-three">
</ul>
JavaScript
var $listOne = $("ul.approach-one"),
$listTwo = $("ul.approach-two"),
$listThree = $("ul.approach-three"),
data = [
{
title: "One"
},
{
title: "Two"
}
];
// Approach 1:
// This approach works but is less performant than the next approach
// The DOM is manipulated once (the append) for every item in the array
for (var i=0; i<data.length; i++) {
var $newLi = $("<li>").html(data[i].title);
$listOne.append($newLi);
}
// Approach 2:
// This approach is more performant
// Only ONE DOM manipulation is actually occurring (the append)
var lis = [];
for (var i=0; i<data.length; i++) {
lis.push($("<li>").html(data[i].title));
}
$listTwo.append(lis);
// Approach 3:
// It is also OK to just build up an HTML string, then append that
var liString = '';
for (var i=0; i<data.length; i++) {
liString += "<li>" + data[i].title + "</li>";
}
$listThree.append(liString);