Emmanuel Akinfulubi

JavaScriptDOM

Add a row to a table in JavaScript

Intermediate · 4 min read

Shopping carts, to-do lists, admin dashboards and score boards all have one thing in common: a table that grows. Someone presses "Add" and a new row appears. JavaScript has a small set of methods made just for this.

In this tutorial you will add a row, with cells in it, to the end of a table when a button is pressed, and then to the top. You should know what an HTML table looks like (table, tr for a row, td for a cell) and what a function is.

The table

Here is the starting table, two rows of two cells:

index.html

<table id="sampleTable" border="1">
  <tr><td>Row1 cell1</td><td>Row1 cell2</td></tr>
  <tr><td>Row2 cell1</td><td>Row2 cell2</td></tr>
</table>
<button id="go">Insert row</button>

rows, cells, insertRow and insertCell

A table element gives you table.rows, a list of its rows. Each row gives you row.cells, a list of its cells. Both lists have a length and can be read by position, like table.rows[0].

To add things there are two methods:

  • table.insertRow(index) makes a new, empty row and returns it.
  • row.insertCell() makes a new, empty cell at the end of that row and returns it.

You could build tr and td elements by hand with document.createElement, but these two do the same job in fewer lines.

Here is the exercise. Try it first if you like, or work through it with me below.

5 Add a row to a table

fair

A table starts with two rows of two cells. Add another row, with cells, when a button is pressed.

Stuck? Three hints, smallest first
  1. 1. table.insertRow() and row.insertCell() exist specifically for this.
  2. 2. A new row with no cells has zero height and looks like nothing happened.
  3. 3. insertRow(-1) appends; insertRow(0) puts it first.

Step 1: add a row

Step 1

const table = document.getElementById('sampleTable');
console.log(table.rows.length); // 2
const row = table.insertRow(-1);
console.log(table.rows.length); // 3

-1 means "at the end". The table now has three rows. But look at the page and nothing seems to have changed.

That is the natural wrong turn here. A row with no cells has no height, so it is invisible. The row is there; there is just nothing in it to show.

Step 2: give the row its cells

insertCell() returns the new cell, so you can set its text on the same line:

Step 2

const table = document.getElementById('sampleTable');
const n = table.rows.length + 1;           // 3: the number of the new row
const row = table.insertRow(-1);
row.insertCell().textContent = `Row${n} cell1`;
row.insertCell().textContent = `Row${n} cell2`;
console.log(row.cells.length);             // 2
console.log(row.cells[1].textContent);     // Row3 cell2

n is worked out before the row is added, so the label matches the row's position. The backtick strings are template literals: ${n} drops the value of n into the text.

Step 3: wrap it in a function and choose where

The index argument is a position. -1 appends; 0 puts the row first. Make it a parameter with -1 as the default:

Step 3

function insert_Row(target, at = -1) {
  const n = target.rows.length + 1;
  const row = target.insertRow(at);
  row.insertCell().textContent = `Row${n} cell1`;
  row.insertCell().textContent = `Row${n} cell2`;
  return row;
}
const table = document.getElementById('sampleTable');
insert_Row(table);       // a third row, at the bottom
insert_Row(table, 0);    // a fourth row, at the top
console.log(table.rows[0].cells[0].textContent); // Row4 cell1
console.log(table.rows[3].cells[0].textContent); // Row3 cell1

Row 4 went in at position 0, which pushed every other row down one place. Rows 1 and 2 are still in their original order between the two new ones.

To connect it to the button, listen for a click:

JavaScript

document.getElementById('go').addEventListener('click', () => insert_Row(table));

Step 4: reading the rows back

table.rows looks like an array, but it isn't one, and it has no map method. Spread it into a real array first with [...]:

Step 4

const table = document.getElementById('sampleTable');
console.log(Array.isArray(table.rows)); // false
console.log(typeof table.rows.map);     // undefined
const textOf = (t) => [...t.rows].map((r) => [...r.cells].map((c) => c.textContent).join(' | '));
console.log(textOf(table)[0]);          // Row1 cell1 | Row1 cell2

textOf turns the whole table into one line of text per row, which is an easy way to check what is in it.

In a real browser, table.rows is also live: it updates the moment you add or remove a row. So a loop like for (let i = 0; i < table.rows.length; i++) insert_Row(table) never ends, because every pass makes the list longer. Save the length in a variable first if you need to loop like that.

The full solution

The panel adds a row at the end, then one at the top, and prints the table after each. Its checks confirm four rows, two cells in each, the right order, and that deleteRow removes one again. Press Run, then use the two buttons in the live demo.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

const table = el('table', { id: 'sampleTable', border: '1' }, [
  el('tr', {}, [el('td', {}, 'Row1 cell1'), el('td', {}, 'Row1 cell2')]),
  el('tr', {}, [el('td', {}, 'Row2 cell1'), el('td', {}, 'Row2 cell2')]),
]);
document.body.appendChild(table);

function insert_Row(target, at = -1) {
  const n = target.rows.length + 1;
  const row = target.insertRow(at);              // -1 appends
  // A row with no cells renders as nothing at all, so always add cells.
  row.insertCell().textContent = `Row${n} cell1`;
  row.insertCell().textContent = `Row${n} cell2`;
  return row;
}

// rows and cells are HTMLCollections, not arrays: no .map on them. Spread first.
const textOf = (t) => [...t.rows].map((r) => [...r.cells].map((c) => c.textContent).join(' | '));

console.log('before:', table.rows.length, 'rows');
insert_Row(table);
console.log('after :', table.rows.length, 'rows');
console.log(textOf(table));

insert_Row(table, 0);
console.log('and one at the top:');
console.log(textOf(table));

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.

14 checks

test('it started with two rows', 2, 2);
test('there are four rows now', table.rows.length, 4);
test('the appended row is third from the start originally', textOf(table)[3], 'Row3 cell1 | Row3 cell2');
test('the row inserted at 0 comes first', textOf(table)[0], 'Row4 cell1 | Row4 cell2');
test('the original rows are still in order', textOf(table).slice(1, 3), ['Row1 cell1 | Row1 cell2', 'Row2 cell1 | Row2 cell2']);
test('every row has two cells', [...table.rows].every((r) => r.cells.length === 2), true);
test('rows is a collection, not an array', Array.isArray(table.rows), false);
test('so it has no map method', typeof table.rows.map, 'undefined');
test('a new row really is a TR', table.rows[0].tagName, 'TR');
test('and its cells are TDs', table.rows[0].cells[0].tagName, 'TD');
test('insertRow returns the row it made', insert_Row(table).tagName, 'TR');
test('so the count went up again', table.rows.length, 5);
test('deleteRow removes one', (() => { table.deleteRow(0); return table.rows.length; })(), 4);
test('and the right one went', textOf(table)[0], 'Row1 cell1 | Row1 cell2');

insertRow and insertCell are part of the table API and save you building tr and td elements by hand. Two details: a row inserted with no cells has no height, so it looks as though nothing happened — always insert cells straight after. And the index argument is a position, where -1 means append and 0 means put it first; the live demo has a button for each so the difference is obvious.

table.rows is a live collection in a real browser, meaning it updates as you change the table rather than being a snapshot. So caching rows.length before a loop that inserts rows gives you an infinite loop.

Common mistakes

  • Adding a row with no cells. It has no height, so it looks like nothing happened. Always insert cells straight after the row.
  • Calling map on table.rows. It is a collection, not an array. Use [...table.rows].map(...).
  • Looping on a length that keeps growing. table.rows updates as you add rows, so i < table.rows.length can loop forever. Store the length first.

Try it yourself

  1. Add a third cell to every new row that shows the time it was added, using new Date().toLocaleTimeString().
  2. Add a "Delete last row" button that calls table.deleteRow(-1). What happens when the table is empty?
  3. Change insert_Row to take the cell texts as an array, like insert_Row(table, ['Apples', '3']), and make one cell per item.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.