I’m trying to create a “feed” using data received from another site. It comes as an array of similar objects. I’ve tried a couple of ways of displaying the data but keep changing my mind on the best way to do it. Currently I’m using jQuery loop through the objects and create the same divs for each one by nesting $(<div>).html()
This uses much less code than my previous method of plain javascript to add new elements but I’m not sure if this is the best use of jQuery. Would there be a better way of doing this?
Possibly creating a new JavaScript object for each array element?
EDIT: here’s a small snippet of code. It’s not closed off and I’ve changed the class names and variables but it’s a rough idea.
$.each(feed.data, function(i, var_name) {
$("<div>").attr({
"id" : var_name.created_time,
"class" : "Post"
}).html(
$("<img>").attr({
"class" : "Picture",
"src" : "some_src" + var_name.id + "/picture"
});
Your method is the least efficient of all the possible methods due to the significant number of function calls made for each individual element.
Although you could add a template engine as suggested, it’s worth learning how to create html strings as well, and will find that wrapping each element in
$()doesn’t really reduce codeSemantically this is easier to read than nesting numerous
$.html()calls alsoIn many cases without a lot of complicated nesting, creating your own strings is less work than creating a template and code to populate template