document.createElement on table,tr,td tags fails IE8

fbynite picture fbynite · Apr 9, 2013 · Viewed 22.2k times · Source

As the title says, I'm having an issue with IE8 (works in FF and IE9). The following code doesn't produce any errors, and if I substitute div,ul,and li; it works. I did some searching and didn't find anything on (table,tr,td) tags not being supported using document.createElement with IE8. Where am I going wrong?

Here is the code:

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    <title>My Page Title</title>
  <script>
    function init() {
      var ele = document.getElementById('content');
      var table = document.createElement('table');
      var tr = document.createElement('tr');
      var td = document.createElement('td');
      var txt = document.createTextNode('IE8');

      td.appendChild(txt);
      tr.appendChild(td);
      table.appendChild(tr);
      ele.appendChild(table);
    }
   </script>
  </head>
  <body onload="init();">
    <div id="content"></div>
  </body>
</html>

Answer

prabeen giri picture prabeen giri · Apr 9, 2013

You can't use only createElement() function to create table, tr, td to create whole table element.

Instead you have to use insertRow(), insertCell() function of table Object

For Reference check this:

http://viralpatel.net/blogs/dynamically-add-remove-rows-in-html-table-using-javascript/

Edit:

Even I was thinking in the same way for IE issues , Buy I found that actually for createElement() to work in IE7 you have to create tbody object and append that to the table object and tr to that tbody object

tb = document.createElement("tbody")  
var tbody  = document.createElement('tbody'); 
table.appendChild(tbody);
var table_row  = document.createElement('tr'); 
tbody.appendChild(table_row)//