shershams shershams - 7 months ago 20
HTML Question

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.

Answer

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).