47

I have a table similar to:

<table id="table1">
<tr>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
</tr>
<tr>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
</tr>
<table>

I want to count the number of td element in a row. I am trying:

document.getElementById('').cells.length;
document.getElementById('').length;
document.getElementById('').getElementsByTagName('td').length;

It did not show actual result.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Muhammad Imran Tariq
  • 22,654
  • 47
  • 125
  • 190
  • By the following you can get the number of rows in a table: document.getElementById('someid').getElementsByTagName('tr').length; – Ripon Al Wasim Oct 12 '12 at 04:20
  • 7
    @pinouchon When one asks for a solution in Javascript, "you have to use jQuery" is not an answer. – Rodrigo Dec 29 '15 at 13:21

11 Answers11

83
document.getElementById('table1').rows[0].cells.length

cells is not a property of a table, rows are. Cells is a property of a row though

Martin Hansen
  • 5,154
  • 3
  • 32
  • 53
  • 9
    This only works in simple cases, where colspan=1 for all cells, and all rows have the same number of columns. (HTML allows rows to have different numbers of columns, in which case the rows with too few columns get blanks at the end.) – David Leppik Sep 03 '13 at 15:14
  • 3
    Not sure what you mean. The question was about the cells in a row. If colspan=2 and missing two still means only one cell. It gets a bit confusing when using rowspan though, but it still is correct, see this fiddle: http://jsfiddle.net/GF6Dr/ If you want a number of how many cells in a table then do the max of all the cells. – Martin Hansen Sep 03 '13 at 19:23
  • 1
    The question title is "count number of **columns**". In his example, all of the `td`s have a colspan of 1, so counting the cells is sufficient. However, ignoring the colspan (number of **columns** a cell spans) is not a good idea if it's possible the colspan is anything besides `1`. – Skeets Jul 05 '19 at 00:50
6

You could do

alert(document.getElementById('table1').rows[0].cells.length)

fiddle here http://jsfiddle.net/TEZ73/

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
5

Why not use reduce so that we can take colspan into account? :)

function getColumns(table) {
    var cellsArray = [];
    var cells = table.rows[0].cells;

    // Cast the cells to an array
    // (there are *cooler* ways of doing this, but this is the fastest by far)
    // Taken from https://stackoverflow.com/a/15144269/6424295
    for(var i=-1, l=cells.length; ++i!==l; cellsArray[i]=cells[i]);

    return cellsArray.reduce(
        (cols, cell) =>
            // Check if the cell is visible and add it / ignore it
            (cell.offsetParent !== null) ? cols += cell.colSpan : cols,
        0
    );
}
Emilio Venegas
  • 546
  • 5
  • 22
3

It's a bad idea to count the td elements to get the number of columns in your table, because td elements can span multiple columns with colspan.

Here's a simple solution using jquery:

var length = 0;
$("tr:first").find("td,th").each(function(){
 var colspan = $(this).attr("colspan");
  if(typeof colspan !== "undefined" && colspan > 0){
   length += parseInt(colspan);
  }else{
        length += 1;
  }
});

$("div").html("number of columns: "+length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
  <td>single</td>
  <td colspan="2">double</td>
  <td>single</td>
  <td>single</td>
</tr>
</table>
<div></div>

For a plain Javascript solution, see Emilio's answer.

Skeets
  • 4,476
  • 2
  • 41
  • 67
2

Count all td in table1:

console.log(
table1.querySelectorAll("td").length
)
<table id="table1">
<tr>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
</tr>
<tr>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
</tr>
<table>

Count all td into each tr of table1.

table1.querySelectorAll("tr").forEach(function(e){
 console.log( e.querySelectorAll("td").length )
})
<table id="table1">
<tr>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
</tr>
<tr>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
</tr>
<table>
NVRM
  • 11,480
  • 1
  • 88
  • 87
2

Here is a terse script taking into account colspan.

numCols will be 0 if the table has no rows, or no columns, and it will be equal to the number of columns regardless of whether some of the cells span multiple rows or columns, as long as the table markup is valid and there are no rows shorter or longer than the number of columns in the table.

    const table = document.querySelector('table')
    const numCols = table.rows[0]
        ? [...table.rows[0].cells]
            .reduce((numCols, cell) => numCols + cell.colSpan , 0)
        : 0
Tigran
  • 2,800
  • 1
  • 19
  • 19
1

First off, when you call getElementById, you need to provide an id. o_O

The only item in your dom with an id is the table element. If you can, you could add ids (make sure they are unique) to your tr elements.

Alternatively, you can use getElementsByTagName('tr') to get a list of tr elements in your document, and then get the number of tds.

here is a fiddle that console logs the results...

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
1

If the colspan or rowspan is all set to 1, counting the children tds will give the correct answer. However, if there are spans, we cannot count the number of columns exactly, even by the maximum number of tds of the rows. Consider the following example:

var mytable = document.getElementById('table')
for (var i=0; i < mytable.rows.length; ++i) {
 document.write(mytable.rows[i].cells.length + "<br>");
}
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
  padding: 3px;
}
<table id="table">
    <thead>
        <tr>
            <th colspan="2">Header</th>
            <th rowspan="2">Hi</th>
        </tr>
        <tr>
            <th>Month</th>
            <th>Savings</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2">hello</td>
            <td>world</td>
        </tr>
        <tr>
            <td>hello</td>
            <td colspan="2">again</td>
        </tr>
    </tbody>
</table>
Han Zhang
  • 352
  • 2
  • 6
0
<table id="table1">
<tr>
  <td colspan=4><input type="text" value="" /></td>

</tr>
<tr>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>
  <td><input type="text" value="" /></td>

</tr>
<table>
<script>
    var row=document.getElementById('table1').rows.length;
    for(i=0;i<row;i++){
    console.log('Row '+parseFloat(i+1)+' : '+document.getElementById('table1').rows[i].cells.length +' column');
    }
</script>

Result:

Row 1 : 1 column
Row 2 : 4 column
Nam Le
  • 1
0

If you add table headers to each column in the table, you can count the number of table headers:

<table id="table1">
   <thead>
      <th></th>
      ...
   </thead>
   <tbody>
      <tr>
         <td><input type="text" value="" /></td>
      </tr>
      ...
<table>

You can then count the number of columns by counting the number of table header elements (assuming each column has a table header element) using:

document.getElementById("table1").querySelectorAll("th").length
-2
$('#table1').find(input).length
ham-sandwich
  • 3,975
  • 10
  • 34
  • 46