Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery execution order question

I am using jQuery to try and construct a table for a web app from a JSON object (using the async getJson call), and I am having difficulty getting to the bottom of the order of execution.

My JS is:

//create table header
$('#peopleDirectory').append(
    "<table><thead><tr><th>column header!</th>"
    +"</tr></thead><tbody>"
);

//iterate through list to create table row:
$.each(jsonArray.members, function(i, membObj) {
    $('#peopleDirectory').append(
            "<tr>"
            + "<td>" + membObj.name + "</td>"
            + "</tr>"
    );
});

//end table
$('#peopleDirectory').append("</tbody></table>");

I create the table and the header row, and then iterate the returned JSON to create the table rows, before closing the table. However, if I use the jQuery $('#peopleDirectory').html() then it produces the table header, then closes the table, and then appends the rows from the JSON (and the table does not appear correctly)

Can anyone help me out with why its executing the appends in this order?

like image 240
rhinds Avatar asked Feb 03 '26 13:02

rhinds


1 Answers

The problem here is probably that you can't append partial HTML to an element like you're doing. When you append <table><tbody>, the browser will actually close the tags too. Then, when you append trs etc., it's no longer inside the table, and the browser will again attempt to correct it, generating broken markup.

You need to first construct the entire markup and only after that append it.

Something like this should work:

var html = "<table><thead><tr><th>column header!</th>"
         + "</tr></thead><tbody>";

$.each(jsonArray.members, function(i, membObj) {
    html += "<tr>"
          + "<td>" + membObj.name + "</td>"
          + "</tr>";
});

html += "</tbody></table>";

$('#peopleDirectory').append(html);
like image 88
Jani Hartikainen Avatar answered Feb 06 '26 04:02

Jani Hartikainen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!