www.fgks.org   »   [go: up one dir, main page]

Click to Rate and Give Feedback
HTML and DHTML Overviews and Tutori...
 How to Build Tables Dynamically
How to Build Tables Dynamically

This article discusses the structure of HTML tables and explains how to use the Document Object Model (DOM) to create them. It also compares the benefits of using table-specific methods instead of the more generic DOM methods. The article assumes you are familiar with JavaScript.

This topic contains the following sections:

Table Structure

Tables consist of rows and columns, arranged in a manner similar to a spreadsheet. The following HTML demonstrates a simple table with five rows and four columns.

<TABLE BORDER="1">
  <THEAD>        
    <TR>
      <TH>Stock Symbol</TH><TH>High</TH><TH>Low</TH><TH>Close</TH>
    </TR>
  </THEAD>
  <TBODY>
    <TR>
      <TD>ABCD</TD><TD>88.625</TD><TD>85.50</TD><TD>85.81</TD>
    </TR>
    <TR>
      <TD>EFGH</TD><TD>102.75</TD><TD>97.50</TD><TD>100.063</TD>
    </TR>
    <TR>
      <TD>IJKL</TD><TD>56.125</TD><TD>54.50</TD><TD>55.688</TD>
    </TR>
    <TR>
      <TD>MNOP</TD><TD>71.75</TD><TD>69.00</TD><TD>69.00</TD>
    </TR>
  </TBODY>
</TABLE>

Tables can can contain multiple tBodies, but only one tHead and one tFoot element. The browser will automatically add (or imply) a tBody element if it is not present, but it will make no distinction about what is placed there. Both th and td elements are placed in a tBody if you do not explicitly create one.

You can use the following HTML elements to create tables.

tableWraps the entire table. Use the table element to apply formatting to the entire table.
tHeadDefines the header section of a table. May contain multiple rows and columns.
tBodyDefines the body of a table. A tBody can also have multiple rows and columns by placing tr and td elements within it.
trDefines a table row. Rows typically host one or more cells, and you can use either the td or th element to define each cell.
tdDefines a table cell.
thDefines a table header cell. The th element is similar to a td element, but it provides additional formatting appropriate for a column heading, such as centering the text and making it bold.
tFootDefines a footer for a table. May contain multiple rows and columns.
captionProvides a brief description. The caption element must be nested within the table; however, the caption text is placed outside the borders of the table. By default, the caption appears at the top, but you can place it at the bottom using the align attribute.
colSpecifies default values, such as width and background color, for the column.
colGroupContains a group of columns. Use colGroup to specify the attributes, such as width and alignment, of a group of columns.

Example: An HTML Table

The following example creates a moderately complex layout using the elements listed in the preceding table. The table contains header, footer, and caption, and it uses multiple tBody elements to add different background colors. This is the reference layout that will be re-created by the dynamic examples later in this article.

<TABLE BORDER="1" BGCOLOR="lightslategray">
<THEAD BGCOLOR="lightskyblue">
  <TR>
    <TH>Stock symbol</TH><TH>High</TH><TH>Low</TH><TH>Close</TH>
  </TR>
</THEAD>
<TBODY BGCOLOR="lemonchiffon">
  <TR>
    <TD>ABCD</TD><TD>88.625</TD><TD>85.50</TD><TD>85.81</TD>
  </TR>
  <TR>
    <TD>EFGH</TD><TD>102.75</TD><TD>97.50</TD><TD>100.063</TD>
  </TR>
</TBODY>
<TBODY BGCOLOR="goldenrod">
  <TR>
    <TD>IJKL</TD><TD>56.125</TD><TD>54.50</TD><TD>55.688</TD>
  </TR>
  <TR>
    <TD>MNOP</TD><TD>71.75</TD><TD>69.00</TD><TD>69.00</TD>
  </TR>
</TBODY>
<TFOOT BGCOLOR="lightskyblue">
  <TR>
    <TD COLSPAN="4">Quotes are delayed by 20 minutes.</TD>
  </TR>
</TFOOT>
<CAPTION ALIGN="BOTTOM" STYLE="font-size=10px;">
  Created using HTML.
</CAPTION>
</TABLE>
This feature requires Microsoft® Internet Explorer 4.0 or later. Click the following icon to install the latest version. Then reload this page to view the sample.

It is easy to use HTML tables to display data that doesn't change. However, consider cases in which the data changes frequently, and updates need to be made often—for example, stock quotes or scores from a sporting event. In these instances, you might want to use the DOM to update these tables dynamically, as described in the following sections.

Creating and Manipulating Tables

Dynamic control of tables is useful when displaying the contents of a database or building a table of calculated data, such as a calendar. When using Dynamic HTML (DHTML) to create a document, you can create objects and set the innerText or innerHTML property of the object. However, because of the specific structure required by tables, the innerText and innerHTML properties of the table and tr objects are read-only. To insert rows and cells, change the contents and attributes of the table, or resize table elements, you must use the DOM.

The "Table Object Model"

The table-specific object model, as defined by the World Wide Web Consortium (W3C) Document Object Model (DOM) Level 1, provide object-specific methods that enable you to create content of tables dynamically. This section explains how to use JavaScript and the table object model to create and manipulate the content of tables.

The table object model consists of:

Methods

The DOM contains the following methods for creating and manipulating tables, rows, and cells.

createTHeadCreates an empty tHead element in the table.
deleteTHeadDeletes the tHead element and its contents from the table.
createTFootCreates an empty tFoot element in the table.
deleteTFootDeletes the tFoot element and its contents from the table.
createCaptionCreates an empty caption element in the table.
deleteCaptionDeletes the caption element and its contents from the table.
insertRowCreates a new row in a table, tBody, tHead, or tFoot, and adds the row to the rows collection of that element.
deleteRowDeletes the specified row in the table and removes the row from the rows collection.
insertCellCreates a new cell in the table row and adds the cell to the cells collection.
deleteCellDeletes the specified cell in the table row and removes the cell from the cells collection.

Collections

Tables consist of multiple collections of elements. You can use indexes to access the members of a collection, or to iterate through it.

The following collections are available.

tBodiesCollection of all tBody objects in the table.
rowsCollection of tr objects (rows) in a tBody, tHead, tFoot, or in a table.
cellsCollection of all cells in the table row or in the entire table.
tBodies

The tBodies collection consists of all the bodies in a table. Unlike tBodies, there can be only one tHead and one tFoot in a table. If more than one tHead is defined, only the first is considered the actual header for the table. The others are added to the tBodies collection.

The table object model does not provide a method for creating tBody elements. However, you can use the DOM to create them. In fact, as you will learn later in this article, you must create a tBody when using the DOM to create a table.

rows

Every table contains a rows collection, which consists of all the rows in a table, including the header and footer rows. You can use the insertRow method to add a row to a table and, consequently, to its rows collection. Each row is equivalent to a tr element in HTML. The following code appends an empty row to the rows collection of a table called oTable.

var oRow = oTable.insertRow(-1);

In Microsoft Internet Explorer, the -1 is optional. It indicates that the insertRow method should append the row to the end of the collection. To insert a row into the middle of a collection, you can pass an index to insertRow, as shown in the following code.

var oRow = oTable.insertRow(3);

The index on the rows collection starts at zero. Therefore, the preceding code inserts a row at the fourth position of the rows collection of oTable. Once a row is created, you can insert cells into it. This is discussed in the next section.

Note  In Internet Explorer, the innerText and innerHTML properties are read-only on the tr object. Therefore, you cannot use them to insert text or HTML into a row. However, you can insert td objects into a row with insertCell and then insert text or HTML into the td objects by setting the innerText or innerHTML property of the cell.

You can access the members of the rows collection by using an index the same way you access an array. Consider the following code, which iterates through the rows of oTable and sets the font to bold for each row. The code uses array syntax to access the individual members of the rows collection. The length property is used to determine the number of elements in a collection.

for (var i = 0; i < oTable.rows.length; i++)
{
  oTable.rows[i].style.fontWeight = "bold";
}
cells

After a row is created, you can add cells to it. Each row exposes a collection of cells; to append cells to the cells collection, call the insertCell method of the row object. By default, insertCell adds cells to the end of the collection, but you can also add a cell in the middle of the collection using a zero-based index.

Note  The insertCell method inserts a td element into the table row, even if the row is part of the tHead of the table. To insert a th element, you must use the DOM methods createElement and appendChild, as described later.

The following example inserts a row into a table and then it inserts a cell into the newly inserted row. Once an empty cell is added to a row, the code inserts HTML into the cell by setting its innerHTML property.

var oRow = oTable.insertRow(-1);
var oCell = oRow.insertCell(-1);
oCell.innerHTML = "Download the latest version of <I>Internet Explorer</I> from here."

As with the rows collection, use array syntax to access members of the cells collection. You can use nested loops to iterate through every cell in every row. The following example sets the color of every cell in the table to red.

var iRow, iCell;

for (iRow = 0; iRow < oTable.rows.length; iRow++)
{
  var oRow = oTable.rows[iRow];
  for (iCell = 0; iCell < oRow.cells.length; iCell++)
  {
    oRow.cells[iCell].style.color = "red";
  }
}

Internet Explorer also provides a cells collection on the table element itself, but this is not a standard DOM property. You can mimic this behavior with getElementsByTagName and traverse all the cells in a single loop, as follows.

var cells = oTable.getElementsByTagName('TD');

for (var i = 0; i < cells.length; i++)
{
  cells[i].style.color = "red";
}

Indexes

Row and cell objects have index properties that indicate their position in the document tree. The following table lists the index properties available on row and cell objects.

rowIndexIndex of the row in the context of the parent table.
sectionRowIndexIndex of the row relative to its table section.
cellIndexIndex of the cell within its parent row.

Example: Table Object Model

The following example uses the table object model to create the example table used throughout this article.

<!-- A rudimentary table -->
<TABLE ID="oTable" BORDER="1" BGCOLOR="lightslategray">
<TBODY ID="oTBody0"></TBODY>
<TBODY ID="oTBody1"></TBODY>
</TABLE>

<SCRIPT LANGUAGE="JavaScript">
window.

function fnInit()
{
  // Declare variables and create the header, footer, and caption.
  var oTHead = oTable.createTHead();
  var oTFoot = oTable.createTFoot();
  var oCaption = oTable.createCaption();
  var oRow, oCell;
  var i, j;

  // Declare stock data that would normally be read in from a stock Web site.
  var heading = new Array();

  heading[0] = "Stock symbol";
  heading[1] = "High";
  heading[2] = "Low";
  heading[3] = "Close";

  var stock = new Array();

  stock[0] = new Array("ABCD","88.625","85.50","85.81");
  stock[1] = new Array("EFGH","102.75","97.50","100.063");
  stock[2] = new Array("IJKL","56.125","54.50","55.688");
  stock[3] = new Array("MNOP","71.75","69.00","69.00");

  // Insert a row into the header.
  oRow = oTHead.insertRow(-1);
  oTHead.setAttribute("bgColor","lightskyblue");

  // Insert cells into the header row.
  for (i=0; i<heading.length; i++)
  {
    oCell = oRow.insertCell(-1);
    oCell.align = "center";
    oCell.style.fontWeight = "bold";
    oCell.innerHTML = heading[i];
  }

  // Insert rows and cells into bodies.
  for (i=0; i<stock.length; i++)
  {
    var oBody = (i<2) ? oTBody0 : oTBody1;
    oRow = oBody.insertRow(-1);
    for (j=0; j<stock[i].length; j++)
    {
      oCell = oRow.insertCell(-1);
      oCell.innerHTML = stock[i][j];
    }
  }

  // Set the background color of the bodies.
  oTBody0.setAttribute("bgColor","lemonchiffon");
  oTBody1.setAttribute("bgColor","goldenrod");

  // Insert rows and cells into the footer row.
  oRow = oTFoot.insertRow();
  oCell = oRow.insertCell();
  oCell.innerHTML = "Quotes are for example only.";
  oCell.colSpan = "4";
  oCell.bgColor = "lightskyblue";

  // Set the innerText of the caption and position it at the bottom of the table.
  oCaption.innerHTML = "Created using Table Object Model."
  oCaption.style.fontSize = "10px";
  oCaption.align = "bottom";
}
</SCRIPT>
This feature requires Microsoft® Internet Explorer 4.0 or later. Click the following icon to install the latest version. Then reload this page to view the sample.

The tBody elements in the preceding example were defined using HTML, because you cannot use the table object model to create tBody elements. As mentioned previously, every table contains at least one tBody element; therefore, you do not need to create one if it is implied by the HTML.

Table Object Model vs. the DOM

The table object model contains methods specific to tables, such as insertRow and insertCell, whereas the DOM is more generic, because it can be applied to all elements. The generic DOM methods support the parent/child/sibling relationships in the document hierarchy with methods such as createElement and appendChild. The DOM is powerful in that it allows you to use script to manipulate any element of a document. For more information about the DOM, see the About the W3C Document Object Model.

You can use the table object model to create and insert an element with a single call to the insertRow method. The DOM, however, requires two distinct steps: first, a call to createElement to create an empty tr element, and then a call to appendChild to insert the element into the document tree. These two steps are required for all elements, including the table itself.

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.

Example: Document Object Model

The following example uses the DOM to create the same table that has been used throughout this article. Although more code is required with the DOM, it allows for more flexibility and control over the table.

<!-- Placeholder for the table -->
<DIV ID="oTableContainer"></DIV>

<SCRIPT LANGUAGE="JavaScript">
window.

function fnInit()
{
  // Declare variables and create the header, footer, and caption.
  var oTable = document.createElement("TABLE");
  var oTHead = document.createElement("THEAD");
  var oTBody0 = document.createElement("TBODY");
  var oTBody1 = document.createElement("TBODY");
  var oTFoot = document.createElement("TFOOT");
  var oCaption = document.createElement("CAPTION");
  var oRow, oCell;
  var i, j;

  // Declare stock data that would normally be read in from a stock Web site.
  var heading = new Array();

  heading[0] = "Stock symbol";
  heading[1] = "High";
  heading[2] = "Low";
  heading[3] = "Close";

  var stock = new Array();

  stock[0] = new Array("ABCD","88.625","85.50","85.81");
  stock[1] = new Array("EFGH","102.75","97.50","100.063");
  stock[2] = new Array("IJKL","56.125","54.50","55.688");
  stock[3] = new Array("MNOP","71.75","69.00","69.00");


  // Insert the created elements into oTable.
  oTable.appendChild(oTHead);
  oTable.appendChild(oTBody0);
  oTable.appendChild(oTBody1);
  oTable.appendChild(oTFoot);
  oTable.appendChild(oCaption);
  
  // Set the table's border width and colors.
  oTable.border=1;
  oTable.bgColor="lightslategray";
  
  // Insert a row into the header and set its background color.
  oRow = document.createElement("TR");
  oTHead.appendChild(oRow);
  oTHead.setAttribute("bgColor","lightskyblue");
  
  // Create and insert cells into the header row.
  for (i=0; i<heading.length; i++)
  {
    oCell = document.createElement("TH");
    oCell.innerHTML = heading[i];
    oRow.appendChild(oCell);
  }
  
  // Insert rows and cells into bodies.
  for (i=0; i<stock.length; i++)
  {
    var oBody = (i<2) ? oTBody0 : oTBody1;
    oRow = document.createElement("TR");
    oBody.appendChild(oRow);
    for (j=0; j<stock[i].length; j++)
    {
      oCell = document.createElement("TD");
      oCell.innerHTML = stock[i][j];
      oRow.appendChild(oCell);
    }
  }
  
  // Set the background color of the first body.
  oTBody0.setAttribute("bgColor","lemonchiffon");
  oTBody1.setAttribute("bgColor","goldenrod");
  
  // Create and insert rows and cells into the footer row.
  oRow = document.createElement("TR");
  oTFoot.appendChild(oRow);
  oCell = document.createElement("TD");
  oRow.appendChild(oCell);
  oCell.innerHTML = "Quotes are for example only.";
  oCell.colSpan = "4";
  oCell.bgColor = "lightskyblue";
  
  // Set the innerHTML of the caption and position it at the bottom of the table.
  oCaption.innerHTML = "Created using Document Object Model."
  oCaption.style.fontSize = "10px";
  oCaption.align = "bottom";
  
  // Insert the table into the document tree.
  oTableContainer.appendChild(oTable);
}
</SCRIPT>
This feature requires Microsoft® Internet Explorer 4.0 or later. Click the following icon to install the latest version. Then reload this page to view the sample.

Sample Game: Unscramble

The following example demonstrates the power of dynamic tables. The Unscramble game includes an image divided into nine tiles, all the same size, which are scrambled in the cells of a table. The player clicks one cell and then another to swap the content of the cells. Unscramble the image to win the game.

The table is created using table object model methods. The processing is done using DOM methods. The swapNode method is used to exchange the contents of two cells.

This feature requires Microsoft® Internet Explorer 4.0 or later. Click the following icon to install the latest version. Then reload this page to view the sample.

Related Topics

Tags What's this?: Add a tag
Community Content
 
Add Community Content
Another IE aggravation.      not-a-windows-fan-boy   |   Edit   |  

"When using Dynamic HTML (DHTML) to create a document, you can create objects and set the innerText or innerHTML property of the object. However, because of the specific structure required by tables, the innerText and innerHTML properties of the table and tr objects are read-only."

Don't you mean "because our engineers couldn't figure out how to make it work ?"

Mozilla does it easily enough. Half my problems with web development come from straightforward DOM Code which works in Mozilla, but requires some complex work-around in IE.

Tags What's this?: Add a tag
Solution: use prototype.js      not-a-windows-fan-boy   |   Edit   |  
This problem can't be that hard. The prototype.js library contains a 20-line workaround to allow IE table elements to be updated.
Tags What's this?: Add a tag
Using innerHTML is not The Way To Do It      Uw Techneut   |   Edit   |  
innerText never works for elements that are not allowed to have textNodes. innerHTML never works for elements that are very specific in what they can contain, so it will work with SPAN and DIV but not with TABLE, that can only contain TBODY, THEAD, TFOOT and CAPTION elements.

Dynamic HTML support has many ways of not working properly in Internet Explorer, but the way it has implemented innerText and innerHTML makes sense.
Tags What's this?: Add a tag
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker
DCSIMG