I am filtering through an array of objects and for each iteration in the array I am taking a template and replacing it with the unique information (properties) from the object that we are currently on. Then the template is appended to the the DOM.
Please look at the first code block and notice that the line of code $('body').append(temp); is inside of the $.each iterator function
I am specifically interested in understanding –
-
Is it because I have left
$('body').append(temp);inside of the$.eachiterator function that the DOM will be appended to every iteration? -
What if this is there is a list of 50 items in the array? In that case for every iteration are we appending something to the DOM?
Code
(function() {
var content = [
{
title: "Speak of the devil and he shall appear",
thumbnail: 'images/bane.jpg',
},
{
title: 'Me the joker',
thumbnail: 'images/Joker.jpg',
},
];
var template = $.trim( $('#blogTemplate').html() );
$.each( content, function( index, obj ) { $(content).each(function() {})
var temp =
template.replace( /{{title}}/ig, obj.title )
.replace( /{{thumbnail}}/ig, obj.thumbnail );
console.log(temp);
$('body').append(temp);
});
})();
In order to solve this problem I believe instead it would be better to build up a string then throw that string into the DOM exactly once. So I have created a new variable called frag and set it equal to an empty string. Then we will filter through the array of objects, and for each object in the array rather than appending to the DOM we are going to say frag+= followed by the stacked .replace methods.
var template = $.trim( $('#blogTemplate').html() );
var frag = '';
$.each( content, function( index, obj ) {
frag +=
template.replace( /{{title}}/ig, obj.title )
.replace( /{{thumbnail}}/ig, obj.thumbnail );
console.log(frag);
});
$('body').append(frag);
})();
And when we are finished we can say $('body').append(frag); outside of the $.each iterator function.
And this leads me on to my final question:
3a. I have moved $('body').append(temp); out of the $.each function, by doing this have I prevented the DOM being updated on every iteration of the $.each function?
the answer to your questions
EDIT: also, if you want to leave the append inside the each block, you should first remove the container element from the DOM, manipulate it, and the append it back to the DOM