Tuesday, February 07, 2023

correct way to use jQuery append

Doing a table fill with AJAX, I was trying to use $('#maintable').append() multiple times in a loop, assuming that the append function is just appending whatever text I supply to it - but it turns out jQuery append actually appends a child element to the parent element. The above syntax is for jQuery and not plain javascript. 

I was ending up with content like

<tr></tr>
<tr></tr>
<tr></tr>
<td>Our data</td>
... and so on.

 So, I must append an entire row with a single append statement. In javascript, the function call can span multiple lines, no problem. Most probably the correct way would be to use maintable.tbody.append, though the snippet below works.  

function showThings(things) {

var maintable = $('#maintable');
maintable.empty();

for (var i = 0; i < things.length; i++) {
maintable.append('<tr><td>Row '+ i + '</td><td>' + things[i][0] + '</td><td>' +
things[i][1] + '</td><td>' +
things[i][2] + '</td><td>' +
things[i][3] + '</td><td>' +
things[i][4] + '</td><td>' +
things[i].length + '</td></tr>');

}

}

No comments:

Post a Comment