Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery appended table adds closing tag at the end of the text automatically. Why?

$('#all_locations').append("<table>");
$('#all_locations').append("<tr><th>City</th></tr>");

$.each(data, function(i, item){
    $('#all_locations').append("<tr>");
    $('#all_locations').append("<td>"+item.city+"</td>");
    $('#all_locations').append("<tr>");
}

$('#all_locations').append("</table>");

Output gotten using alert($('#all_locations').html());

<table></table>
<tr><th>City</th></tr>
<tr></tr><td>Seattle</td>
<tr></tr><td>Chicago</td>

This code fires when ajax call is finished. Any ideas why is it doing so?

Assume that data variable is the valid JSON object.

like image 525
Sherzod Avatar asked Dec 01 '22 01:12

Sherzod


1 Answers

Despite the abstraction that jQuery offers, you are operating on elements in the DOM, not tags in the HTML source.

jQuery('<table>') is shorthand for jQuery(document.createElement('table')).

You need to append your table rows to the table, not to the container (and likewise, the cells need to be added to the rows).

like image 79
Quentin Avatar answered Jan 25 '23 10:01

Quentin