I am wondering what is the correct way to make new elements with jQuery. For example, say that I have a table, into where I want to append some rows according to a list of objects that I have, so the way I do it currently is like so:
var list =
[
{
name: 'Banana',
cost: 100
},
{
name: 'Apple',
cost: 200
},
{
name: 'Orange',
cost: 300
}
];
var appendThis = '';
for(var key in list)
{
var product = list[key];
appendThis += '<tr>';
appendThis += '<td>' + product.name + '</td>';
appendThis += '<td>' + product.cost + '</td>';
appendThis += '</tr>';
}
$('#producttable').empty().append(appendThis);
Fiddle: https://jsfiddle.net/ahvonenj/ywjbrrak/
But I have heard that concatenating string and appending the rows like that is a good way to do it and instead I should create tr
and td
elements, into which I append the data from the list and then append those elements in to the HTML table.
So if that is the seemingly correct way to do it, how exactly is it done? I have only ever created div
elements programmatically with $('</div>')
, but I am not sure how to create a tr
like that and on top of that append the programmatically created td
in to the programmatically created tr
.
Does it work like this perhaps:
var $row = $('</tr>').append($('<\td>').append('TD CONTENT'));