Update a table cell by row and column in JavaScript
Intermediate · 3 min read
A spreadsheet changes one cell when you type into it. A live score board updates one score. A seating chart marks one seat as taken. Each of these needs to reach one cell of a table by its row and column and change what is inside.
In this tutorial you will write changeContent, a function that takes a table, a row number, a column number and some text, and puts the text in that cell. It will also refuse, with a clear message, when the cell doesn't exist. You should know what an HTML table is and how arrays are numbered.
How to reach one cell
Here is the table:
<table id="myTable" border="1">
<tr><td>Row1 cell1</td><td>Row1 cell2</td></tr>
<tr><td>Row2 cell1</td><td>Row2 cell2</td></tr>
<tr><td>Row3 cell1</td><td>Row3 cell2</td></tr>
</table>
table.rows is the list of rows, and each row's cells is its list of cells. Both start counting at 0, just like arrays. So table.rows[1].cells[1] is the second cell of the second row: the one that says "Row2 cell2".
textContent
cell.textContent = 'hello' replaces everything inside the cell with that text. It treats what you give it as plain text, never as HTML, which turns out to matter a lot.
Here is the exercise. Try it yourself first, or follow along.
6 Update one cell of a table
fairWrite a function taking a row number, a column number and a string, and put that string in that cell.
Stuck? Three hints, smallest first
- 1.
table.rows[r].cells[c]reaches the cell. Both are zero-based. - 2. An out-of-range index gives
undefined, and the next property read throws. - 3. Prefer
textContenttoinnerHTMLfor text you did not write yourself.
Step 1: change one cell
const table = document.getElementById('myTable');
table.rows[1].cells[1].textContent = 'changed!';
console.log(table.rows[1].cells[1].textContent); // changed!
console.log(table.rows[1].cells[0].textContent); // Row2 cell1
The target cell changed and its neighbor didn't. Remember the numbering: row 1 is the second row on the screen.
Step 2: make it a function
function changeContent(target, rowIndex, columnIndex, text) {
target.rows[rowIndex].cells[columnIndex].textContent = text;
}
const table = document.getElementById('myTable');
changeContent(table, 0, 0, 'first');
console.log(table.rows[0].cells[0].textContent); // first
This works for every cell that exists. Now try one that doesn't. The table has three rows, numbered 0 to 2:
changeContent(table, 9, 0, 'x');
// TypeError: Cannot read properties of undefined (reading 'cells')
table.rows[9] is undefined, and asking undefined for .cells throws. The message names the symptom ("undefined") but not the cause (row 9 doesn't exist). Someone reading it has to work backwards to find what went wrong.
Step 3: check each level and say what went wrong
Check the row, then the cell, before you touch anything. When one is missing, throw an error that says what the valid range is:
function changeContent(target, rowIndex, columnIndex, text) {
const row = target.rows[rowIndex];
if (!row) throw new RangeError(`no row ${rowIndex}; rows are 0 to ${target.rows.length - 1}`);
const cell = row.cells[columnIndex];
if (!cell) throw new RangeError(`no column ${columnIndex} in row ${rowIndex}`);
cell.textContent = text;
return cell;
}
const table = document.getElementById('myTable');
try {
changeContent(table, 9, 0, 'x');
} catch (e) {
console.log(e.message); // no row 9; rows are 0 to 2
}
try {
changeContent(table, 0, 9, 'x');
} catch (e) {
console.log(e.message); // no column 9 in row 0
}
RangeError is JavaScript's built-in error for "this number is outside the allowed range". A negative number is caught too: rows[-1] is undefined, so the same check refuses it.
Returning the cell is a small extra. It lets the caller do more with it, like adding a class to highlight the change.
Step 4: why textContent and not innerHTML
innerHTML also sets what is inside an element, but it reads the text as HTML. Here is what textContent does with some markup:
const table = document.getElementById('myTable');
const cell = table.rows[2].cells[0];
cell.textContent = '<b>not bold</b>';
console.log(cell.textContent); // <b>not bold</b>
console.log(cell.children.length); // 0
The tags show up on the page as ordinary characters, and no b element is created. With innerHTML, the browser would have built a real bold element. That sounds harmless, but if the text came from a user, the same door lets them add any HTML they like, including code that runs. Use textContent for text, and keep innerHTML for markup you wrote yourself.
The full solution
The panel changes a cell, tries a bad row, a bad column and a negative index, and puts markup in with textContent. Its checks confirm only the target cell changes and every bad position is refused with a RangeError. Press Run, then try an out-of-range row in the live demo.
allow-scripts only, so it cannot reach this page.const table = el('table', { id: 'myTable', border: '1' }, [1, 2, 3].map((n) =>
el('tr', {}, [el('td', {}, `Row${n} cell1`), el('td', {}, `Row${n} cell2`)])
));
document.body.appendChild(table);
function changeContent(target, rowIndex, columnIndex, text) {
const row = target.rows[rowIndex];
// Guard both levels: an out-of-range index gives undefined, and reading
// .cells on undefined throws a TypeError.
if (!row) throw new RangeError(`no row ${rowIndex}; rows are 0 to ${target.rows.length - 1}`);
const cell = row.cells[columnIndex];
if (!cell) throw new RangeError(`no column ${columnIndex} in row ${rowIndex}`);
cell.textContent = text; // textContent, not innerHTML
return cell;
}
const textOf = (t) => [...t.rows].map((r) => [...r.cells].map((c) => c.textContent).join(' | '));
const failure = (r, c) => {
try { changeContent(table, r, c, 'x'); return 'no error'; } catch (e) { return e.constructor.name; }
};
console.log('before:', textOf(table));
changeContent(table, 1, 1, 'changed!');
console.log('after :', textOf(table));
console.log('bad row :', failure(9, 0));
console.log('bad column:', failure(0, 9));
// textContent treats markup as text. innerHTML would not, which is the whole
// reason to prefer it for anything a user supplied.
changeContent(table, 2, 0, '<b>not bold</b>');
console.log('markup put in with textContent stays text:', table.rows[2].cells[0].textContent);
Output
12 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 12 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the target cell changed', table.rows[1].cells[1].textContent, 'changed!');
test('its neighbour did not', table.rows[1].cells[0].textContent, 'Row2 cell1');
test('nor did the row above', textOf(table)[0], 'Row1 cell1 | Row1 cell2');
test('indexes are zero-based, so 0,0 is the first cell', changeContent(table, 0, 0, 'first').textContent, 'first');
test('there are still three rows', table.rows.length, 3);
test('and two columns', table.rows[0].cells.length, 2);
test('a row that does not exist is refused', failure(9, 0), 'RangeError');
test('a column that does not exist is refused', failure(0, 9), 'RangeError');
test('a negative index is refused too', failure(-1, 0), 'RangeError');
test('markup set via textContent stays text', table.rows[2].cells[0].textContent, '<b>not bold</b>');
test('so it created no element', table.rows[2].cells[0].children.length, 0);
test('the function returns the cell it changed', changeContent(table, 0, 1, 'z').tagName, 'TD');
table.rows[r].cells[c] is the path, and both indexes are zero-based. The guard matters more than it looks: rows[9] is undefined, so rows[9].cells throws TypeError: Cannot read properties of undefined — an error that names the symptom and not the cause. Checking each level and throwing a message that says what the valid range is turns a puzzle into a sentence. Try an out-of-range row in the live demo.
textContent rather than innerHTML is the security habit. The assertion shows '<b>not bold</b>' arriving as visible text with no element created. Had that been innerHTML, any text originating from a user could inject markup, and the same door lets in a <script> or an onerror handler. Use innerHTML only for markup you wrote yourself.
Common mistakes
- Counting from 1. Rows and cells start at 0. The first cell is
rows[0].cells[0]. - Not checking the row exists.
rows[9].cellsthrows aTypeErrorthat doesn't say which row was wrong. Check first and throw a clear message. - Using
innerHTMLfor user text. It turns the text into HTML.textContentkeeps it as text.
Try it yourself
- After changing a cell, give it a yellow background for one second with
setTimeout, so the change is easy to spot. - Write
readCell(table, row, column)that returns a cell's text, with the same range checks. - Change the row message so it also says how many columns that row has.