Main Page

Core DOM methods

If you want to accomplish this with the Core DOM methods, your code would look something like this:
//create the table
var oTable = document.createElement(“table”);
oTable.setAttribute(“border”, “1”);
oTable.setAttribute(“width”, “100%”);
//create the tbody
var oTBody = document.createElement(“tbody”);
oTable.appendChild(oTBody);
//create the first row
var oTR1 = document.createElement(“tr”);
oTBody.appendChild(oTR1);
var oTD11 = document.createElement(“td”);
oTD11.appendChild(document.createTextNode(“Cell 1,1”));
oTR1.appendChild(oTD11);
var oTD21 = document.createElement(“td”);
oTD21.appendChild(document.createTextNode(“Cell 2,1”));
oTR1.appendChild(oTD21);
//create the second row
var oTR2 = document.createElement(“tr”);
oTBody.appendChild(oTR2);
var oTD12 = document.createElement(“td”);
oTD12.appendChild(document.createTextNode(“Cell 1,2”));
oTR2.appendChild(oTD12);
var oTD22 = document.createElement(“td”);
oTD22.appendChild(document.createTextNode(“Cell 2,2”));
oTR2.appendChild(oTD22);
//add the table to the document body
document.body.appendChild(oTable);
This code is quite verbose and a little hard to follow. To facilitate building tables, the HTML DOM adds
several properties and methods to the
<table/>
,
<tbody/>
, and
<tr/>
elements.
The
<table/>
element adds the following:
?
caption
— pointer to the
<caption/>
element (if it exists)
?
tBodies
— collection of
<tbody/>
elements
?
tFoot
— pointer to the
<tfoot/>
element (if it exists)
?
tHead
— pointer to the
<thead/>
element (if it exists)
?
rows
— collection of all rows in the table
?
createTHead()
— creates a
<thead/>
element and places it into the table
?
createTFoot()
— creates a
<tfoot/>
element and places it into the table
?
createCaption()
— creates a
<caption/>
element and places it into the table
?
deleteTHead()
— deletes the
<thead/>
element
?
deleteTFoot()
— deletes the
<tfoot/>
element
180
Chapter 6
09_579088 ch06.qxd 3/28/05 11:37 AM Page 180


JavaScript EditorFree JavaScript Editor     Ajax Editor


©