Java Reference
In-Depth Information
nodeType property. If it's equal to 1, then the child node is an element. Next, create a <th/> element,
and a text node containing the current node's nodeName, which you append to the header cell. And
fi nally, append the <th/> element to the row.
The second part of displayDogs() builds the body of the table and populates it with data. It is similar
in look and function to the header-generation code.
var tableBody = document.createElement(“tbody”);
for (var i = 0; i < dogNodes.length; i++)
{
var tableRow = document.createElement(“tr”);
//Inner loop code here
tableBody.appendChild(tableRow);
}
table.appendChild(tableBody);
First, create the <tbody/> element, and then loop through the dogNodes node list, cycling through the
<dog/> elements. Inside this loop, create a <tr/> element and append it to the table's body. When the
loop exits, append the <tbody/> element to the table. Now look at the inner loop, which adds data cells
to the row.
for (var j = 0; j < dogNodes[i].childNodes.length; j++)
{
var currentNode = dogNodes[i].childNodes[j];
if (currentNode.nodeType == 1)
{
var tableDataCell = document.createElement(“td”);
var textData = document.createTextNode(
currentNode.firstChild.nodeValue
);
tableDataCell.appendChild(textData);
tableRow.appendChild(tableDataCell);
}
tableBody.appendChild(tableRow);
}
This inner loop cycles through the child elements of <dog/> . First, assign the currentNode variable to
reference the current node. This enables you to access this node a little more easily (much less typing!).
Next, check the node's type. Again, DOM-based browsers count whitespace as child nodes, so you need
to make sure the current node is an element. When it's confi rmed that the current node is an element,
create a <td/> element and a text node containing the text of currentNode . Append the text node to
the data cell, and append the data cell to the table row created in the outer for loop.
At this point, the table is completed, so add it to the HTML page. You do this with the following:
document.body.appendChild(table);
}
Search WWH ::




Custom Search