<table> 元素是 HTML 中最複雜的結構之一。要建立表格,通常得處理表示表格列、儲存格、表頭等多種標籤,因此若只用核心 DOM 方法建立,往往需要撰寫大量程式碼。以下示範如何用 DOM 建立一個簡單表格:
<table border="1" width="100%">
<tbody>
<tr>
<td>Cell 1,1</td>
<td>Cell 2,1</td>
</tr>
<tr>
<td>Cell 1,2</td>
<td>Cell 2,2</td>
</tr>
</tbody>
</table>
若純用核心 DOM 方法建立這些元素,程式碼會相當冗長:
//創建table
var table = document.createElement("table");
table.border = 1;
table.width = "100%";
//創建tbody
var tbody = document.createElement("tbody");
table.appendChild(tbody);
//創建第一行
var row1 = document.createElement("tr");
tbody.appendChild(row1);
var cell1_1 = document.createElement("td");
cell1_1.appendChild(document.createTextNode("Cell 1,1"));
row1.appendChild(cell1_1);
var cell2_1 = document.createElement("td");
cell2_1.appendChild(document.createTextNode("Cell 2,1"));
row1.appendChild(cell2_1);
//創建第二行
var row2 = document.createElement("tr");
tbody.appendChild(row2);
var cell1_2 = document.createElement("td");
cell1_2.appendChild(document.createTextNode("Cell 1,2"));
row2.appendChild(cell1_2);
var cell2_2 = document.createElement("td");
cell2_2.appendChild(document.createTextNode("Cell 2,2"));
row2.appendChild(cell2_2);
//將表格插入到文檔中
document.body.appendChild(table);
顯然,這種 DOM 寫法又長又不好懂。為方便建立表格,HTML DOM 特別為 <table>、<tbody> 與 <tr> 元素新增了一些屬性與方法。
為 <table> 元素新增的屬性與方法:
為 <tbody> 元素新增的屬性與方法:
為 <tr> 元素新增的屬性與方法:
善用這些屬性與方法,能大幅減少建立表格所需的程式碼。改寫後如下:
//創建table
var table = document.createElement("table");
table.border = 1;
table.width = "100%";
//創建tbody
var tbody = document.createElement("tbody");
table.appendChild(tbody);
tbody.insertRow(0);
tbody.rows[0].insertCell(0);
tbody.rows[0].cells[0].appendChild(document.createTextNode("Cell 1,1"));
tbody.rows[0].insertCell(1);
tbody.rows[0].cells[1].appendChild(document.createTextNode("Cell 2,1"));
//創建第二行
tbody.insertRow(1);
tbody.rows[1].insertCell(0);
tbody.rows[1].cells[0].appendChild(document.createTextNode("Cell 1,2"));
tbody.rows[1].insertCell(1);
tbody.rows[1].cells[1].appendChild(document.createTextNode("Cell 2,2"));
//將表格添加到文檔中
document.body.appendChild(table);
這次建立 <table> 與 <tbody> 的程式碼不變,差別在於建立列的環節改用了 HTML DOM 的表格屬性與方法。建立第一行時,透過 <tbody> 呼叫 insertRow() 並傳入 0,表示新列放在位置 0,之後即可用 tbody.rows[0] 參照該列。建立儲存格的方式類似,透過 <tr> 呼叫 insertCell() 並傳入位置,再以 tbody.rows[0].cells[0] 參照新儲存格。