Generate HTML table from 2D JavaScript array -
in javascript, possible generate html table 2d array? syntax writing html tables tends verbose, want generate html table 2d javascript array, shown:
[["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"]] would become:
<table border="1"> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table> so i'm trying write javascript function return table 2d javascript array, shown:
function gettable(array){ //take 2d javascript string array input, , return html table. }
here's function use dom instead of string concatenation.
function createtable(tabledata) { var table = document.createelement('table'); var tablebody = document.createelement('tbody'); tabledata.foreach(function(rowdata) { var row = document.createelement('tr'); rowdata.foreach(function(celldata) { var cell = document.createelement('td'); cell.appendchild(document.createtextnode(celldata)); row.appendchild(cell); }); tablebody.appendchild(row); }); table.appendchild(tablebody); document.body.appendchild(table); } createtable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"]]);
Comments
Post a Comment