Create table using Javascript
Slightly shorter code using insertRow
and insertCell
:
function tableCreate(){ var body = document.body, tbl = document.createElement('table'); tbl.style.width = '100px'; tbl.style.border = '1px solid black'; for(var i = 0; i < 3; i++){ var tr = tbl.insertRow(); for(var j = 0; j < 2; j++){ if(i == 2 && j == 1){ break; } else { var td = tr.insertCell(); td.appendChild(document.createTextNode('Cell')); td.style.border = '1px solid black'; if(i == 1 && j == 1){ td.setAttribute('rowSpan', '2'); } } } } body.appendChild(tbl);}tableCreate();
Also, this doesn't use some "bad practices", such as setting a border
attribute instead of using CSS, and it accesses the body
through document.body
instead of document.getElementsByTagName('body')[0]
;
This should work (from a few alterations to your code above).
function tableCreate() { var body = document.getElementsByTagName('body')[0]; var tbl = document.createElement('table'); tbl.style.width = '100%'; tbl.setAttribute('border', '1'); var tbdy = document.createElement('tbody'); for (var i = 0; i < 3; i++) { var tr = document.createElement('tr'); for (var j = 0; j < 2; j++) { if (i == 2 && j == 1) { break } else { var td = document.createElement('td'); td.appendChild(document.createTextNode('\u0020')) i == 1 && j == 1 ? td.setAttribute('rowSpan', '2') : null; tr.appendChild(td) } } tbdy.appendChild(tr); } tbl.appendChild(tbdy); body.appendChild(tbl)}tableCreate();
function addTable() { var myTableDiv = document.getElementById("myDynamicTable"); var table = document.createElement('TABLE'); table.border = '1'; var tableBody = document.createElement('TBODY'); table.appendChild(tableBody); for (var i = 0; i < 3; i++) { var tr = document.createElement('TR'); tableBody.appendChild(tr); for (var j = 0; j < 4; j++) { var td = document.createElement('TD'); td.width = '75'; td.appendChild(document.createTextNode("Cell " + i + "," + j)); tr.appendChild(td); } } myTableDiv.appendChild(table);}addTable();
<div id="myDynamicTable"></div>