點擊頁面按鈕,即時在文檔中插入一個帶藍色背景、邊框的 100×100 像素表格,包含一行一列。此為早期原生 DOM 操作教學範例。
function creates() {
// 創建 table 元素
var newiframes = document.createElement("TABLE");
newiframes.id = "t1";
newiframes.width = "100";
newiframes.border = "1";
newiframes.height = "100";
newiframes.align = "left";
newiframes.style.background = "blue";
// 插入行與儲存格
newiframes.insertRow();
newiframes.rows[0].insertCell();
// 插入到 body 前
document.body.insertBefore(newiframes);
}
setAttribute 或直接操作 DOM 屬性(如 newiframes.style.width = '100px')。insertBefore 需要參考節點,原碼缺少第二參數,實際會報錯。應改為 document.body.appendChild(newiframes) 或指定參考節點。id="t1",導致無效 HTML。應動態生成唯一 ID。<table> 應包含 <tbody>,現代瀏覽器會自動補全但最好顯式創建。function addTable() {
const table = document.createElement('table');
table.style.cssText = 'width:100px;height:100px;border:1px solid #000;background:blue;margin:5px;';
const tbody = document.createElement('tbody');
const tr = document.createElement('tr');
const td = document.createElement('td');
tr.appendChild(td);
tbody.appendChild(tr);
table.appendChild(tbody);
document.body.appendChild(table);
}