views:

246

answers:

2

A bit weird... ...if running in IE8 quirks mode or in compatibility view mode, the table added by the following code doesn't render. Can anyone tell me why, because it is not obvious to me..?

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<script>
function AddTable()
{
  var table = document.createElement('table');
  var row = document.createElement('tr');
  table.appendChild(row);
  var cell = document.createElement('td');
  cell.innerHTML='abc';
  row.appendChild(cell);
  var divContainer = document.getElementById('divContainer');
  divContainer.appendChild(table);
}
</script>
</head>
<body>
<div id='divContainer'>
</div>
<input type='button' value='add table' onclick='javascript:AddTable()' />
</body>
</html>
+2  A: 

Try adding a tbody element

Instead of

  var row = document.createElement('tr');
  table.appendChild(row);

do

  var tbody = document.createElement('tbody');
  var row = document.createElement('tr');
  tbody.appendChild(row);
  table.appendChild(tbody);
Alohci
+1 Thanks, yes, that makes it render the table, but has some interesting effects on how it is rendered... Not sure why yet, will see what I can find.
KristoferA - Huagati.com
+1  A: 

Microsoft has a page that may illuminate what's going on.

http://msdn.microsoft.com/en-us/library/ms532998(VS.85).aspx#TOM_Create

For dynamically building tables they advocate the "Table Object Model", which uses methods like insertRow() and insertCell() to do the job you're doing with the DOM methodscreateElement() and appendChild(). It's also OK if you use the DOM methods, but "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."

The table object model works in the couple of browsers I tested it in (Chrome and Firefox on the Mac), so it may not be a bad idea to familiarize yourself with it. Or if you want to stick with the DOM methods, add the tBody element, because IE requires it.

If you add the following code to the end of your AddTable() method you'll see how the two compare (mainly, the second table will have a tBody in it). And it will render in IE8.

 // now the Table Object Model way
  table = document.createElement('table');
  row = table.insertRow(-1) ;
  cell = row.insertCell(-1) ;
  cell.innerHTML='def';
  divContainer.appendChild(table);

Hope this helps.

brainjam
KristoferA - Huagati.com