fbynite
fbynite

Reputation: 2661

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

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>

Upvotes: 4

Views: 33114

Answers (3)

saravanan
saravanan

Reputation: 11

try this:

  var ele = document.getElementById('content');
  var table = document.createElement('table');
  ele.appendChild(table);
  var tr = document.createElement('tr');
  table.appendChild(tr);
  var td = document.createElement('td');
  tr.appendChild(td);
  var txt = document.createTextNode('IE8');
  td.appendChild(txt);

Upvotes: 1

prabeen giri
prabeen giri

Reputation: 803

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)// 

Upvotes: 3

raj-nt
raj-nt

Reputation: 149

just add <!DOCTYPE html> in markup. In IE7 and above default rendering without DOCTYPE is Quirks mode (IE5).

Upvotes: 1

Related Questions