View Full Version : Creating array from table column

02-22-2007, 08:42 PM
Hey guys

I'm writing an app for my school's site that will make an excel-like spreadsheet in which someone can type how many credits they have in science, etc...

My problem is that I'm not sure how to store the numeric values of a table column in an array to add them up (in order to calculate the total science credits, for example). I really don't want to make individual IDs for 160 table cells and add them individually :eek:

Could someone point me in the right direction on how to get all of the TDs in a table row in an array?


02-22-2007, 09:11 PM
tds = tr.getElemensByTagName('td');
the only problem will be this will fetch all the tds even td's of the tables nested in this tr so its a good practise to filter out those

function getTDs(tr) {
var tds = tr.getElementsByTagName('td');
target = [];
for ( i = 0; i < tds.length; i++ ) {
if ( tds[i].parentNode == tr ) {
return target;

but, its generally an overkill

02-22-2007, 09:13 PM
getElementsByTagName() returns an array of matching elements. Example:

var sum = 0, tableCells = document.getElementsByTagName("td");

for (var i = 0; i < tableCells.length; i++) {
sum += parseFloat(document.getElementsByTagName("td")[i].firstChild.data);
This script iterates through every td element in the document and adds their content together. firstChild.data is the text node child of the cell; you need to convert it to a number before you can use it.

Note: shyam beat me to the post.

02-25-2007, 06:20 PM
Give the table containing the credits an ID like "credits"

var totals = new Array()

function credCount() {
var rows=document.getElementById("credits").getElementsByTagName("tr")
var cols=rows[i].getElementsByTagName("td")
// Do something with the totals

Total as many columns as you like.