Using the innerHTML Property

When you use the innerHTML property, you need to be careful.  Take a look at this simplified Javascript sample code:
 
    var new_legend = document.createElement("div");
    new_legend.innerHTML = "<table>";
    new_legend.innerHTML = new_legend.innerHTML + "<tr><td colspan=2 align=center>Legend</td></tr>";
 
    //Add legend entries
    for (var i = 0; i < legend_count; i++) 
    {
         new_legend.innerHTML = new_legend.innerHTML + "<tr><td>something1</td><td>csomething else</td></tr>";
    }
    new_legend.innerHTML = new_legend.innerHTML + "</table>";
 
.NET is very helpful, and makes the first assignment (new_legend.innerHTML = "<table>";) into well-formed HTML.  That is, it adds the "<tbody></table>" tags for you.  Therefore, the rest of the HTML that you build into the innerHTML is not part of the table.  Not what you wanted.

The simple trick around this is to just build up the HTML in a variable and assign it to the innerHTML once your HTML is complete and well-formed, like this:

    var new_legend = document.createElement("div");
    var new_legend_text = "<table>";
    new_legend_text = new_legend_text + "<tr><td colspan=2 align=center>Legend</td></tr>";

 
    //Add legend entries
    for (var i = 0; i < legend_count; i++) 
    {
         new_legend_text = new_legend_text + "<tr><td>something</td><td>something else</td></tr>";
    }
    new_legend_text = new_legend_text + "</table>";
    new_legend.innerHTML = new_legend_text;

 

Note that the Internet Explorer Developer Toolbar I mentioned in a previous post is a great tool to help diagnose this sort of thing because you can look into the DOM live and see what is going on with your assembled HTML and even add or change existing attribute values.

Have a thought or opinion?