JavaScript & DOMで動的table生成
できない。
最後の手段として、stringでhtmlを吐き出すというのがあるが、これはできれば使いたくない。
<html> <head> <title></title> <script type="text/javascript"> function start(tbl) { // get the reference for the body // var body = document.getElementsByTagName("body")[0]; if (typeof tbl == "table") tbl = document.getElementsById(tbl); // creates a <table> element and a <tbody> element var tblBody = document.createElement("tbody"); // creating all cells for (var j = 0; j < 2; j++) { // creates a table row var row = document.createElement("tr"); for (var i = 0; i < 2; i++) { // Create a <td> element and a text node, make the text // node the contents of the <td>, and put the <td> at // the end of the table row var cell = document.createElement("td"); var cellText = document.createTextNode("繧サ繝ォ縺ッ "+j+" 陦^Z "+i+" 蛻^Z 縺ァ縺^Z"); cell.appendChild(cellText); row.appendChild(cell); } // add the row to the end of the table body tblBody.appendChild(row); } // put the <tbody> in the <table> tbl.appendChild(tblBody); test-table_2.html:33Uncaught TypeError: Object tblid has no method 'appendChild' test-table_2.html:33Uncaught TypeError: Object tblid has no method 'appendChild' // appends <table> into <body> // body.appendChild(tbl); // sets the border attribute of tbl to 2; tbl.setAttribute("border", "2"); } </script> </head> <body> <table id="tblid"> </table> <p> test </p> <button onclick="start('tblid');">Display Table</button> </body> </html>
こいつを読み込ませたら
Uncaught TypeError: Object tblid has no method 'appendChild' 13 Uncaught TypeError: Object tblid has no method 'appendChild'
と言われる。tableの子ノードってtbodyじゃないの常識的に考えて。