Reputation:
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.
Upvotes: 0
Views: 23915
Reputation: 19
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.
Upvotes: 2
Reputation: 57354
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.
Upvotes: 1
Reputation: 83173
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
Upvotes: 7
Reputation: 73057
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.
Upvotes: 1
Reputation: 11056
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.
Upvotes: 3
Reputation: 13003
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.
Upvotes: 1