JavaScript innerHTML problem

Recently I was updating a JavaScript function which simply added another element to a page, complete with content. The innerHTML function was used. However, I was very confused that some HTML elements I’d added using innerHTML were stripped on rendering.

Problem: I was trying to add a new row plus cells to an existing table on a page. It seems like innerHTML in Firefox strips new rows and cells (tr and td). Example:

<table id="table1">
<tr>
<td><h3>Existing header</h3></td>
</tr>
</table>
<script>
var newRow = document.createElement("tr");
newRow.innerHTML = '\
<tr>\
<td><h3>New header</h3>\
</tr>\
';
document.getElementById("table1").appendChild(newRow);
</script>

This would simply output:
<table id="table1">
<tr>
<td><h3>Existing header</h3></td>
</tr>
<h3>New header</h3>
</table>

…Which is incorrect by web standards and is not much to work with.

Solution: Instead of inserting the new element (the <tr>) after the innerHTML string is added, I did it before. It seems like the browser doesn’t like that we add elements that are strictly associated with tables unless it actually knows for sure that they’ll be added to the correct structure.

This is the simple solution for disappearing tds and rows:

<script>
var newRow = document.createElement("tr");
document.getElementById("table1").appendChild(newRow);
newRow.innerHTML = '\
<tr>\
<td><h3>New header</h3>\
</tr>\
';
</script>