tags:

views:

320

answers:

1

Could someone explain why this piece of script won't work in IE? It seems to work alright in Firefox. I'm new with the appendChild() API.

<html>
<head>
<script type='text/javascript'>

function makeTable()
{
   nTable=document.createElement('table');
   nTable.setAttribute('id','myTable');
   nTable.setAttribute('border','1');

   nRow1=document.createElement('tr');
   nData11=document.createElement('td');
   nData11.setAttribute('colspan','2');
   nCenter11=document.createElement('center');
   nBold=document.createElement('b');
   nBold.appendChild(document.createTextNode('Title'));
   nCenter11.appendChild(nBold);
   nData11.appendChild(nCenter11);
   nRow1.appendChild(nData11);

   nRow2=document.createElement('tr');
   nData21=document.createElement('td');
   nCenter21=document.createElement('center');
  nCenter21.appendChild(document.createTextNode('21'));
  nData21.appendChild(nCenter21);
  nData22=document.createElement('td');
   nCenter22=document.createElement('center');
  nCenter22.appendChild(document.createTextNode('22'));
  nData22.appendChild(nCenter22);
  nRow2.appendChild(nData21);
  nRow2.appendChild(nData22);

  nTable.appendChild(nRow1);
  nTable.appendChild(nRow2);

  alert('Almost there !');
  try
  {
   document.getElementById('container').appendChild(nTable);
  }
  catch(e)
  {
    alert(e.message);
  }
   return;

}

</script>
</head>
<body>
<div id='container'>
</div>
<input type=button value='Go' onclick='makeTable();'>
</body>
</html>
+3  A: 

See http://msdn.microsoft.com/en-us/library/ms532998(VS.85).aspx#TOM_DOM. Similarly to what Crescent Fresh mentioned in his comment, IE needs a tbody element inserted into the table so that you can use the DOM:

Note Internet Explorer requires that you create a tBody element and insert it into the table when using the DOM. Since you are manipulating the document tree directly, Internet Explorer does not create the tBody, which is automatically implied when using HTML.

Andy E