tags:

views:

1070

answers:

7

How do you calculate the number of <td> elements in a particular <tr>?

I didn't specify id or name to access directly, we have to use the document.getElementsByTagName concept.

+4  A: 

You can use something like the following:

var rowIndex = 0; // rowindex, in this case the first row of your table
var table = document.getElementById('mytable'); // table to perform search on
var row = table.getElementsByTagName('tr')[rowIndex];
var cells = row.getElementsByTagName('td');
var cellCount = cells.length;
alert(cellCount); // will return the number of cells in the row
Aron Rotteveel
you could add the check for "table" to support multiple tables.
Gene
You're right, thanks.
Aron Rotteveel
+1  A: 

Something like

var tot = 0;
var trs = document.getElementsByTagName("tr");
for (i = 0; i < trs.length; i++) {
    tds = trs[i].getElementsByTagName("td");
    tot += tds.length;
}

At the end, tot hold the total number of all td elements "sons" of tr elements.

Davide Gualano
+3  A: 

document.getElementsByTagName returns an array of elements, so you should be able to do something like this:

var totals = new Array();

var tbl = document.getElementById('yourTableId');
var rows = tbl.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
    totals.push(rows[i].getElementsByTagName('td').length;
}

...

// total cells in row 1
totals[0];
// in row 2
totals[1];
// etc.
Ian Oxley
+1  A: 
var trs = document.getElementsByTagName('tr');
for(var i=0;i<trs.length;i++){
  alert("Number of tds in row '+(i+1)+' is ' + tr[i].getElementsByTagName('td').length);
}

will alert the number of <td>s in each <tr> on the page.

Phil
+1  A: 

If you use the jQuery library, it should be as simple as this.

$("table tr:eq(0) > td").length

You can use anything as a selector as you would CSS3

$("#mytableid tr").eq(0).children("td").length

Would be another way to do it.

Kent Fredric
A: 
tr.cells.length

Is an easier way to spell it.

bobince
+2  A: 

bobince has the correct answer. I tried to give him some love, but I am new with a 0 rep.

tr.cells.length is the quickest way to get what you want.

Now, the assumption is that you already have a reference to the tr. If you don't, at some point you have to have a reference to the table. In the DOM, the table element has an array (actually an HTMLCollection) called rows.

table.rows[r].cells[c]

will give you the address of any cell where r = the index of the row and c = the index of the cell within that row.