In a previous tutorial we showed you how to dynamically add and remove rows from a table. This is a very useful technique, but sometimes you might need to add entire bits of HTML into a table as just a string. In this situation, things can get a little tricky.
Let’s say you have a table, and you need to insert HTML into it. Either you have a AJAX call that returns a string of HTML, or you just like slapping HTML into a table. Sometimes that’s just what you have to do. In the tutorial mentioned above, DOM methods were used to insert rows. While this is the preferred and suggested method, from time to time you end up with this situation:
var table = document.getElementById(‘myTable’);
table.innerHTML += html;
Now, this may seem like the perfect way to do things, but there are several problems. First off, most browsers require and even add a tbody
tag. So right off the bat we are selecting the wrong element to add our HTML to.
However, that isn’t the biggest problem we will run into. In Internet Explorer, innerHTML
is read only on tables. Yeap, read only. Since we all like to be cross-browser compatible, the solution above is unacceptable.
At this point, using jQuery would be a good option, as it would allow you to convert an HTML string into something you can append to the table. At the very least it provides more enhanced tools for dealing with tables, as well having hoards of plugins for this exact kind of task.
That being said, all you will be doing with jQuery is converting the string into usable DOM objects, and if you absolutely have to do it with plan ol’ javascript, it is possible (of course). It actually only takes a few simple lines of Javascript:
var table = document.getElementById(‘myTable’).getElementsByTagName(‘tbody’)[0];
var tmpTable = document.createElement(‘div’);
tmpTable.innerHTML = ‘<table><tbody>’ + html + ‘</tbody></table>’;
var tr = tmpTable.getElementsByTagName(‘tr’)[0].cloneNode(true);
table.appendChild(tr);
Basically what we are doing is creating a temporary table to convert our string into usable DOM objects. We do this by setting the innerHTML of div (which we create), which allows use to then get our original table row as a DOM object. From there it’s as easy as appending it to our table body.
So there you have it, converting a string to DOM objects for use in a table. That wraps it up for this tutorial. Just remember, when you need coding help all you have to do is Switch On The Code.