Create a table dynamically in JavaScript
Intermediate · 3 min read
Sometimes the table you need doesn't exist until the user asks for it. A multiplication chart, a seating plan, a calendar month, a game board: you know how many rows and columns you want, and JavaScript builds the whole thing.
In this tutorial you will write createTable(rows, columns), which builds a table where every cell names its own position, like Row-0 Column-0. You should know what a for loop is and what an HTML table looks like.
Building elements from nothing
document.createElement('table') makes a new table element. It exists in memory but isn't on the page yet. Nothing shows until you add it to an element that is on the page, with appendChild.
A table element also has insertRow(), which adds a row and returns it, and each row has insertCell(), which adds a cell and returns it.
Loops inside loops
A table is a grid, so you need two loops. The outer loop goes once per row. Inside it, the inner loop goes once per column. Here is the same shape with plain text, so you can see the order things happen in:
for (let r = 0; r < 2; r++) {
for (let c = 0; c < 3; c++) {
console.log(`Row-${r} Column-${c}`);
}
}
// Row-0 Column-0, Row-0 Column-1, Row-0 Column-2,
// then Row-1 Column-0, Row-1 Column-1, Row-1 Column-2
The inner loop runs all the way through for each pass of the outer one. That is exactly how you fill a table: one row at a time, left to right.
Here is the exercise. Try it first if you like, then read on.
7 Build a table from scratch
fairTake a number of rows and columns, and build the table, filling each cell with its own position, like Row-0 Column-0.
Stuck? Three hints, smallest first
- 1. Two nested loops: rows outside, columns inside.
- 2. Build the whole table before putting it in the page, so the browser lays out once instead of per cell.
- 3. A
DocumentFragmentis the standard way to stage nodes off-document.
Step 1: one row of cells
Start small: make a table with a single row and fill it.
const table = document.createElement('table');
const row = table.insertRow();
for (let c = 0; c < 4; c++) {
row.insertCell().textContent = `Row-0 Column-${c}`;
}
console.log(row.cells.length); // 4
console.log(row.cells[3].textContent); // Row-0 Column-3
Step 2: wrap it in the row loop
Now put that inside a loop over the rows, and turn the whole thing into a function:
function createTable(rows, columns) {
const table = document.createElement('table');
table.setAttribute('border', '1');
for (let r = 0; r < rows; r++) {
const row = table.insertRow();
for (let c = 0; c < columns; c++) {
row.insertCell().textContent = `Row-${r} Column-${c}`;
}
}
return table;
}
const t = createTable(3, 4);
console.log(t.rows.length); // 3
console.log(t.rows[2].cells[3].textContent); // Row-2 Column-3
The border attribute just draws lines so you can see the cells. The function returns the table rather than adding it to the page itself, which means you decide where it goes.
Step 3: put it on the page, once
function createTable(rows, columns) {
const table = document.createElement('table');
for (let r = 0; r < rows; r++) {
const row = table.insertRow();
for (let c = 0; c < columns; c++) {
row.insertCell().textContent = `Row-${r} Column-${c}`;
}
}
return table;
}
const host = document.getElementById('host');
host.textContent = ''; // clear any old table
host.appendChild(createTable(3, 4));
console.log(host.querySelector('table').rows.length); // 3
host is an empty div with id="host" on the page. Setting its textContent to '' removes whatever was inside, so pressing the button twice doesn't stack two tables.
Notice the order: the table is built completely while it is off the page, then added in one go. If you add it first and then fill it, the browser may redo its layout work on every cell you add. For 12 cells nobody would notice; for a few thousand rows it is the difference between instant and visibly slow.
Step 4: refuse nonsense sizes
What should createTable(2.5, 2) or createTable(-1, 2) do? Half a row makes no sense. Check the inputs at the top and throw:
function createTable(rows, columns) {
if (!Number.isInteger(rows) || !Number.isInteger(columns) || rows < 0 || columns < 0) {
throw new RangeError('rows and columns must be whole numbers, 0 or above');
}
const table = document.createElement('table');
for (let r = 0; r < rows; r++) {
const row = table.insertRow();
for (let c = 0; c < columns; c++) {
row.insertCell().textContent = `Row-${r} Column-${c}`;
}
}
return table;
}
try {
createTable(2.5, 2);
} catch (e) {
console.log(e.name); // RangeError
}
console.log(createTable(0, 0).rows.length); // 0
Number.isInteger is true only for whole numbers. Zero is allowed: it gives an empty table, which is a fair answer to "zero rows, please".
The full solution
The panel builds a 3 by 4 table, puts it on the page and prints the grid. Its checks confirm 12 unique cells that follow the pattern, empty tables for zero sizes, and a RangeError for fractions and negative numbers. Press Run, then change the numbers in the live demo.
allow-scripts only, so it cannot reach this page.function createTable(rows, columns) {
if (!Number.isInteger(rows) || !Number.isInteger(columns) || rows < 0 || columns < 0) {
throw new RangeError('rows and columns must be whole numbers, 0 or above');
}
// Built detached from the document, then attached once. A browser can lay out
// and paint after every insertion if you build in place; this way it does that
// work a single time.
const table = document.createElement('table');
table.setAttribute('border', '1');
for (let r = 0; r < rows; r++) {
const row = table.insertRow();
for (let c = 0; c < columns; c++) {
row.insertCell().textContent = `Row-${r} Column-${c}`;
}
}
return table;
}
const host = el('div', { id: 'host' });
document.body.appendChild(host);
host.appendChild(createTable(3, 4));
const grid = (t) => [...t.rows].map((r) => [...r.cells].map((c) => c.textContent));
const built = host.querySelector('table');
const refused = (r, c) => {
try { createTable(r, c); return 'no error'; } catch (e) { return e.constructor.name; }
};
console.log('3 x 4:');
for (const row of grid(built)) console.log(' ', row.join(' '));
console.log('cells:', built.rows.length * built.rows[0].cells.length);
console.log('0 x 0 gives an empty table:', createTable(0, 0).rows.length, 'rows');
console.log('a fractional count is refused:', refused(2.5, 2));
Output
14 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 14 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('three rows were made', built.rows.length, 3);
test('each with four cells', [...built.rows].every((r) => r.cells.length === 4), true);
test('twelve cells in total', [...built.rows].reduce((n, r) => n + r.cells.length, 0), 12);
test('the first cell names its own position', grid(built)[0][0], 'Row-0 Column-0');
test('the last cell too', grid(built)[2][3], 'Row-2 Column-3');
test('every cell is unique', new Set(grid(built).flat()).size, 12);
test('every cell follows the pattern', grid(built).flat().every((t) => /^Row-\d+ Column-\d+$/.test(t)), true);
test('the table went into the page', built.parentNode === host, true);
test('zero rows gives an empty table', createTable(0, 0).rows.length, 0);
test('zero columns still gives rows', createTable(3, 0).rows.length, 3);
test('but with no cells', [...createTable(3, 0).rows].every((r) => r.cells.length === 0), true);
test('a single cell', grid(createTable(1, 1)), [['Row-0 Column-0']]);
test('a fractional count is refused', refused(2.5, 2), 'RangeError');
test('a negative count is refused', refused(-1, 2), 'RangeError');
Building the table detached and attaching it once is the habit worth forming. Insert into a live document inside a loop and the browser may recalculate layout on every pass; build it off-document and it does that work once. For a 3×4 table nobody could measure the difference, but the same loop over a few thousand rows is the difference between instant and visibly slow.
Note host.textContent = '' in the demo as the way to empty a container. It is shorter than looping over removeChild, and unlike innerHTML = '' it involves no markup parsing at all.
Common mistakes
- Swapping the loops. Columns in the outer loop and rows inside gives you the wrong shape. Rows go outside.
- Using
<=in the loop.r <= rowsmakes one row too many. Count from 0 and stop before the number. - Forgetting to clear the old table. Each click adds another one underneath. Empty the container first with
host.textContent = ''.
Try it yourself
- Make a multiplication table: fill each cell with
(r + 1) * (c + 1)instead of its position. - Add a header row of
thcells that sayColumn-0,Column-1and so on. (Hint: create them withdocument.createElement('th').) - Color every other row with a light background so long tables are easier to read.