I wrote the following javascript to dynamically build a calendar and append it to a designated div. It works and the calendar looks fine in the browser.
$('#Calendar').append('<table><thead><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th><th>Sunday</th></thead><tr>');
for (i = 0; i <= loop; i++) {
if ((i == 7) || (i == 14) || (i == 21) || (i == 28) || (i == 35)) {
$('#Calendar').append(loopDate.getDate() + "</tr><tr>");
$('#Calendar').append('<td>' + loopDate.getDate() + '</td>');
loopDate.addDays(1);
} else {
$('#Calendar').append('<td>' + loopDate.getDate() + '</td>');
loopDate.addDays(1);
}
}
$('#Calendar').append('</table>');
}
However, when I inspect the resulting HTML for the page I see that my <tr></tr> are not landing in the correct place. There also appears to be an extraneous appended . Can someone please explain to me why this is happening?
<div id="Calendar">
<div></div>
<table>
<thead>
<tr>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
<th>Saturday</th>
<th>Sunday</th>
</tr></thead>
<tbody>
<tr></tr>
</tbody>
</table>
<td>26</td>
<td>27</td>
<td>28</td>
<td>29</td>
<td>30</td>
<td>31</td>
<td>1</td>
<tr></tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<tr></tr>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
<td>15</td>
<tr></tr>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
<td>21</td>
<td>22</td>
<tr></tr>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26</td>
<td>27</td>
<td>28</td>
<td>29</td>
</div>
jQuery methods such as
append()manipulate the browser’s DOM tree.The DOM holds complete HTML elements. You can’t put in half of a tag.
Instead, you can concatenate HTML into a string (or, for better performance, an array), then put the complete HTML string into the DOM at once.