JSFiddle - React, Tailwind, and code Playground
by apasaja
HTML
<!DOCTYPE html>
<html>
<head>
<title>
Javascript array to table
</title>
<style>
/* [COSMETICS - DOES NOT MATTER] */
html, body {
font-family: arial;
}
table {
border-collapse: collapse;
}
table tr td {
border: 1px solid #000;
padding: 10px;
}
</style>
</head>
<body>
<!-- ALL YOU NEED IS A CONTAINER -->
<div id="container"></div>
</body>
</html>
JavaScript
window.addEventListener("load", function(){
// LET'S SAY THAT WE HAVE A SIMPLE FLAT ARRAY
var data = ["doge", "cate", "birb", "doggo", "moon moon", "awkward seal"];
// DRAW HTML TABLE
var perrow = 3, // 3 items per row
count = 0, // Flag for current cell
table = document.createElement("table"),
row = table.insertRow();
for (var i of data) {
var cell = row.insertCell();
cell.innerHTML = i;
// You can also attach a click listener if you want
cell.addEventListener("click", function(){
alert("FOO!");
});
// Break into next row
count++;
if (count%perrow==0) {
row = table.insertRow();
}
}
// ATTACH TABLE TO CONTAINER
document.querySeletorAll("#container").appendChild(table);
});