views:

40

answers:

2

I have a table which looks like this:

<table id='t'>
    <thead>
        ....
    </thead>
    <tbody id='t_tbody'>
    </tbody>
</table>
  • thead is filled with content

  • tbody is empty

I want to use javascript to add this (for example) to t_tbody:

<tr>
    <td>Name</td>
    <td>Points</td>
    <td>Information</td>
</tr>

How can I do this? I need a function which adds the above to t_tbody.

Note that simply using

document.getElementById('t_tbody').innerHtml+="<tr>...</tr>"

works fine in FF, but not in IE.

Also note that I need to use raw javascript (ie. no frameworks) for this project, as I am finishing a project which has already been mostly completed using raw javascript.

+4  A: 
var tr = document.createElement("tr");

var td = document.createElement("td");
td.innerHTML = "Name";
tr.appendChild(td);

var td2 = document.createElement("td");
td2.innerHTML = "Points";
tr.appendChild(td2);

var td3 = document.createElement("td");
td3.innerHTML = "Information";
tr.appendChild(td3);

document.getElementById('t_tbody').appendChild(tr);
Gregoire
sorry it was not the add function but the appendChild one. last line it is because your tbody do not have id
Gregoire
I've edited the html so that the table and tbody have different id's. Could you update your javascript? I think that would help me understand better. Thanks! I've also deleted the comment above yours as it didn't really make sense.
Cam
@incrediman: done :)
Gregoire
Perfect, thanks!
Cam
Was just going to answer the same! +1
Jacob Relkin
+2  A: 

The answer by Gregoire is indeed the most "correct" way of doing this, however do note that IE does not seem to complain if you are editing innerHTML of elements not yet in the DOM. Thus the solution could be shortened to:

var tr = document.createElement('tr');

tr.innerHTML = "<td>Name</td><td>Points</td><td>Information</td>";

document.getElementById('t_tbody').appendChild(tr);    
nemetroid
Turns out this doesn't work in FF, strangely. What ends up hapenning is that Name, Points, and Information are printed against each other with no whitespace - completely ignoring the fact that they're td's in a table. Like this: "NamePointsInformation". I didn't end up testing in IE... thanks anyways though!
Cam