HTML / JavaScript Reference - Table

HTML syntax, and how to reference specific cells with JavaScript

Overview

The <table> tag is used to organize data into a table structure. Two other tags are needed when creating tables: <tr> (table row), and <td> (table data). First, the <table> tag begins the table. Then, for every row (the elements going up and down), there needs to be a <tr> tag. Within a row there has to be at least one <td> tag. It is after this tag that data can appear. Practically any other tag can go after a <td> tag. Open and close each of the three tags. Place data between the <td> and </td> tags.

Referencing table rows and cells

The JavaScript below uses the table's rows collection, and the row's cells collection.

Example table

Upper Left Upper Right
Lower Left Lower Right

The results

Between here:

: and here should be the results of the JavaScript.

Source

Public Domain

The HTML and JavaScript listed below are released to the public domain. Read the Terms of Use for details. The contents of this page are still copyrighted.

HTML

<table id="tblTest" border="1">
	<tr>
		<td>Upper Left</td>
		<td>Upper Right</td>
	</tr>
	<tr>
		<td>Lower Left</td>
		<td>Lower Right</td>
	</tr>
</table>

JavaScript

function getCellByRowCol(rowNum, colNum)
{
	var tableElem = document.getElementById('tblTest');
	var rowElem = tableElem.rows[rowNum];
	var tdValue = rowElem.cells[colNum].innerHTML;
	return tdValue;
}
document.writeln('Row 0, Col 0: ');
document.writeln(getCellByRowCol(0,0));
document.writeln('<br />');

document.writeln('Row 0, Col 1: ');
document.writeln(getCellByRowCol(0,1));
document.writeln('<br />');

document.writeln('Row 1, Col 0: ');
document.writeln(getCellByRowCol(1,0));
document.writeln('<br />');

document.writeln('Row 1, Col 1: ');
document.writeln(getCellByRowCol(1,1));

Browser Compatibility

This code makes use of W3 DOM standards, so you'll need a compliant browser.

2005-09-03 - Tested in Firefox 1.0.6, Mozilla 1.7.11, Opera 8.02, Internet Explorer 6.0, Netscape 7.1, and Nescape 6.1.

About this page: