I am trying to create HTML using JQuery. I have a JQuery script which creates a HTML table:
$('<table>').attr('cellspacing', '5').addClass('blocksTable')
.append('<tbody><tr><td>Name</td>')
.append('<td><input type="text" value="" name="textBlockNames" class="textField"/></td></tr>')
.append('<tr><td>Locale</td>')
.append('<td><input type="text" value="" name="textBlockLocales" class="textField"/></td></tr>')
.append('<tr><td>Content</td>')
.append('<td><input type="text" value="" name="textBlockContents" class="textField"/></td></tr></tbody>')
.append('</table>')
.appendTo($("#idParentBlocksTable"));
But the table is generated like this:
<table class="blocksTable" cellspacing="5">
<tbody>
<tr>
<td>Name</td>
</tr>
<tr>
<td>Locale</td>
</tr>
<tr>
<td>Content</td>
</tr>
</tbody>
<td>
<input class="textField" type="text" name="textBlockNames" value="">
</td>
<td>
<input class="textField" type="text" name="textBlockLocales" value="">
</td>
<td>
<input class="textField" type="text" name="textBlockContents" value="">
</td>
</table>
While it should be generated like this:
<table class="blocksTable" cellspacing="5">
<tbody>
<tr>
<td> Name </td>
<td>
<input class="textField" type="text" name="textBlockNames" value="">
</td>
</tr>
<tr>
<td> Locale </td>
<td>
<input class="textField" type="text" name="textBlockLocales" value="">
</td>
</tr>
<tr>
<td> Content </td>
<td>
<input class="textField" type="text" name="textBlockContents" value="">
</td>
</tr>
</tbody>
</table>
What I am doing wrong here? I don’t know how more clearly explain the problem so I am typing anything here because the system doesn’t allow me to submit the question.
When you’re calling
jQuery doesn’t change the HTML source of the page but adds one (or more) DOM node(s). So the HTML is automatically fixed (here the row and cell are closed)
What you should do is build some HTML string and append it :
Note that appending elements to the DOM is costly. You should prefer building a large HTML string and append it once over appending many small elements.