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

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


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


It's best practice to create a string of your HTML to append and run one .append() call on that string:

//declare our output variablevar output = '<table><tr><th>City</th></tr>';//iterate through data$.each(data, function(i, item){    //add to output variable    output += '<tr><td>' + item.city + '</td></tr>';}//append the output to the DOM$('#all_locations').append(output);

It's pretty common to see people pushing items into an array and joining that array for the append:

//declare our output variable (array)var output = ['<table><tr><th>City</th></tr>'];//iterate through data$.each(data, function(i, item){    //add to output variable    output.push('<tr><td>' + item.city + '</td></tr>');}//append the output to the DOM after joining it together into a string$('#all_locations').append(output.join(''));


Add an id to the tag to solve this problem.Then add the sub element to that id instead of parent element.

$(function(){    for(var lvl=0;lvl<5;lvl++)    {        $("#tblId tbody").append("<tr id="+lvl+"/>");                           for(var fchr=0;fchr<3;fchr++)            $("#tblId tbody #"+lvl).append("<td>Val"+lvl+fchr+"</td>");    }    alert($('#tblId').html());});

Running example, see here:http://jsfiddle.net/WHscf/1/