Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
In the last section, we witnessed how the DOM is structured with a collection of methods and properties. We will go ahead and work with the creation of an HTML table dynamically and traverse through its rows and columns, which demonstrates the usage of DOM with JavaScript. The DOM methods presented in the example also apply for XML apart from HTML/XHTML. The following is the code snippet in an HTML page for creating an HTML table dynamically. This HTML table displays a multiplication table from 1–10 in the web page after execution.
<html>
<head>
<title>Working with JavaScript and DOM</title>
<script>
function createTable() {
// get the reference for the body element
var body = document.getElementsByTagName("body")[0];
var prg = document.createElement("p");
prg.data = "Example demonstrating the creation of HTML Table
dynamically";
body.appendChild(prg);
// creates a <table> element and a <tbody> element
var table = document.createElement("table");
var tableBody = document.createElement("tbody");
// creating all cells
for (var i = 1; i <= 10; i++) {
// creating a table row
var row = document.createElement("tr");
for (var j = 1; j <= 10; j++) {
// Creating a <td> element, associating text node with it,
// and appending at the end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode(i*j);
cell.appendChild(cellText);
row.appendChild(cell);
}
// adding the row to the end of the table body
tableBody.appendChild(row);
}
// appending <tbody> in the <table>
table.appendChild(tableBody);
// appending <table> into <body>
body.appendChild(table);
// setting the border attribute of table to 1;
table.setAttribute("border", "1");
}
</script>
</head>
<body onload="createTable()">
</body>
</html>