Dynamic Tables In JavaScript for IE and Firefox

阅读更多

http://www.sweetvision.com/2007/04/08/dynamic-tables-in-javascript-for-ie-and-firefox/

 

Recently I had the “pleasure” of dynamic creating some tables in JavaScript. In the process, I ran into and interesting issue or two. The first issue is that you cannot just append elements into a

element in IE . It will work, but IE will not render the rows. In IE you must create a element, append the element to the
element, then append your rows to your element. This does not follow the W3C Row groups specification for the table specification which states that: “Table rows may be grouped into a table head, table foot, and one or more table body sections, using the THEAD, TFOOT and TBODY elements, respectively.” Note that the W3C specification states ‘may be’ whereas IE treats it as “must be.” So, the following will get you nothing in IE but will work fine in Firefox :

  
  
  
  
var myTable = document.createElement("table"); var myRow = document.createElement("tr"); var myCell = document.createElement("td"); myCell.innerHTML = "Hello World!"; myTable.appendChild(myRow); myRow .appendChild(myCell);

This will render a table in both IE and Firefox

:

  
  
  
  
var myTable = document.createElement("table"); var myTbody = document.createElement("tbody"); var myRow = document.createElement("tr"); var myCell = document.createElement("td"); myCell.innerHTML = "Hello World!"; myTable.appendChild(myTbody); myTbody.appendChild(myRow); myRow.appendChild(myCell);

So now we have a table that renders in both IE and Firefox but there is still an issue remaining. Now in Firefox there is a space between the top of the table and the first row that you cannot get rid of. This is not going to be evident in all situations but will be in enough situations to be a problem. The reason for the space is that when you add a

to a table in Firefox it appears to reserve or auto include the and elements in the table. This is most likely done because the W3C specification states that you must have a and if you have a . In order to prevent this extra space you need to add the and the and set their height to 0px or their display to none or something of the sort unless, of course, you are going to use them.

  
  
  
  
var myTable = document.createElement("table"); var myThead = document.createElement("thead"); myThead.style.height = 0px; var myTfoot = document.createElement("tfoot"); myTfoot.style.height = 0px; var myTbody = document.createElement("tbody"); var myRow = document.createElement("tr"); var myCell = document.createElement("td"); myCell.innerHTML = "Hello World!"; myTable.appendChild(myThead); myTable.appendChild(myTfoot); myTable.appendChild(myTbody); myTbody.appendChild(myRow); myRow.appendChild(myCell);

This gives you a way to render tables that match in both IE and Firefox with the same code.

你可能感兴趣的:(IE,Firefox,JavaScript)