JavaScript Snippet: A Table Generated By JavaScript; With Example - Rigid Structure Full-Page HTML Table

Posted at

3 rows x 2 columns.
code:
"<table><tbody>" + "\
" +
(new Array(3)).join(',').split(',').reduce(function(carry, current, index){
carry.push("<tr>" + (new Array(3)).join("<td></td>") + "</tr>");
return carry;
}, []).join("\
")
+ "\
" + "</tbody></table>";


result:
<table><tbody>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
</tbody></table>


- naturally, you can make it dynamic as will but keep in-mind to +1 the column size (due to way array is generated).

- the ARRAY.join(',').split(',') convert undefined-filled array, to an empty-string-filled array, which is controllable by ARRAY.reduce method.





this code will generate a 4x4-table (using a similar technique to the code above) that will fill the entire (100%) of page, with rigid structure (meaning the size of the "table-cells" will not change with content):
<!doctype html>
<html dir="ltr" lang="en-US">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<style type="text/css" media="all">
html,body,[content],table{
width:100%;
height:100%;
padding:0;
margin:0;
border-collapse:collapse;
overflow:hidden;
}
html{ background: none rgba(90,90,90,.8); }
td{ border:1px dashed rgba(90,90,90,.9); }

td{ width:25%; }
tr{ height:25%;}

td{
background-image: url('http://icompile.eladkarako.com/img/apple-touch-icon.png');
background-position: center center;
background-repeat: no-repeat;
background-origin: border-box;
background-size: cover;
}
</style>
</head>
<body><div content></div>
<script>
document.querySelector('div[content]').innerHTML =
"<table><tbody>" + "\
" +
(new Array(4)).join(',').split(',').reduce(function(carry, current, index){
carry.push("<tr>" + (new Array(4+1)).join("<td></td>") + "</tr>");
return carry;
}, []).join("\
")
+ "\
" + "</tbody></table>"
;
</script></body></html>


and here is an example (you can right click it to open in new tab, to see it full screen, or view its source)