6

I have searched for a solution to this issue everywhere but nothing has worked. I have successfully pulled the first column but I am unable to pull the 2nd column. The following code pulls the entire 1st column successfully.

I changed .cells to [1] and it pulls nothing. I have tried :nth-child(1) but that doesn't work either. I feel I am missing something very trivial. Any help is very much appreciated.

function F0416()
{
    var tab = document.getElementById('partTable');
    var l = tab.rows.length;

    var s = '';
    for ( var i = 0; i < l; i++ )
    {
        var tr = tab.rows[i];

        var cll = tr.cells[0];

        s += ' ' + cll.innerText;
    }
    document.write(s);
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
JohnB
  • 133
  • 1
  • 2
  • 13
  • 1
    `tab.rows.length;` ?? – Grijesh Chauhan Feb 28 '14 at 14:00
  • Should work with `cells[1]` - there is probably an empty column that you are missing. – tucuxi Feb 28 '14 at 14:01
  • Could you show us your table's html? In addition, from your current code, you don't want to get the entire column, you just want to get the text in every cell of the row and concat it together. – SaidbakR Feb 28 '14 at 14:01
  • Solution Found - I found that tucuxi and user13500 were dead on. I figured it was something simple. I went back and deleted the 1st two rows of my table that are not needed and my code is now working as is. I want to thank everyone for their contributions. Have a good weekend. – JohnB Feb 28 '14 at 16:13
  • 1
    @sємsєм: No, he will get the column, not the row. – user13500 Feb 28 '14 at 16:14

3 Answers3

8

First and foremost. Never ever use l (lower case el) as a variable. It is far to similar to 1 (one). Also be careful with upper case "o", and upper-case "i". Lowercase "o" is also often disliked.

It might look OK now, but when you review it in 6 months or a year, perhaps not so much. Also consider others might have to both read and modify your code.

Enough about that.


Your code, as it is, should work. If you do not get the desired result then the problem is elsewhere.

Make it reusable

However, to simplify the code and make it easier to re-use, you can add a parameter for id of the table as well as desired column. Resulting function could be something like this, with some extra checks:

function getColumn(table_id, col) {
    var tab = document.getElementById(table_id);
    var n = tab.rows.length;
    var i, s = null, tr, td;

    // First check that col is not less then 0
    if (col < 0) {
        return null;
    }

    for (i = 0; i < n; i++) {
        tr = tab.rows[i];
        if (tr.cells.length > col) { // Check that cell exists before you try
            td = tr.cells[col];      // to access it.
            s += ' ' + td.innerText;
        } // Here you could say else { return null; } if you want it to fail
          // when requested column is out of bounds. It depends.
    }
    return s;
}

var txt = getColumn('partTable', 2);

Check for failure

By using null as initial value for s, we can compare returned result with null to see if it was successful.

if (txt === null) {
    // Report error, or at least not work on "txt".
}

Simplify

Once you really understand it you can, if you want, simplify the loop to something like this:

for (i = 0; i < n; i++) {
    if (tab.rows[i].cells.length > col) {
        s += ' ' + tab.rows[i].cells[col].innerText;
    }
}

Use Array:

If you are going to use the cells one by one the best approach would be to return an Array instead of a string. Then you can loop the array, or if you want it as a string simply join it with desired delimiter. This would most likely be the most useful and reusable function.

// In function:
arr = [];

// In loop:
arr.push(tab.rows[i].cells[col].innerText);

var cells = getColumn("the_id", 2);
var text = cells.join(' ');

Demo:

Fiddle demo with array


Speed.

If your table cells does not contain any <script> or <style>, which they should not, you can also consider using textContent over innerText. Especially if table is large. It is a much faster. Here is a short article on the subject from Kelly Norton:

user13500
  • 3,817
  • 2
  • 26
  • 33
  • This approach will fail in case there is a cell that spans over multiple rows (eg. `rowspan="2"`) because that cell will shift the following rows sideways. so their cells array index won't represent the index of the column in the rendered table anymore. – gilad905 Aug 15 '23 at 11:46
1
// This pulls all columns
function getAllCells(table) {
    var result = [];

    for(var i = 0, j = 0, l = table.rows.length, l2 = 0; i < l; i++) {
        for(j = 0, l2 = table.rows[i].cells.length; j < l2; j++) {
            result.push(table.rows[i].cells[j].innerText);
        }
    }

    return result.join(',');
}
  • Andres thank you for your answer. It is what I was just attempting but unsuccessfully. Once I get it implemented I will let you know how it goes. I have been coding only for a very short time so could take a some time. :) – JohnB Feb 28 '14 at 14:36
  • Oh by the way my table is 10 cells X 56 rows. I am pulling the entire column because I am doing a text compare with the data in all the rows. – JohnB Feb 28 '14 at 14:55
  • OP is asking to retrieve all cells in ***one*** column, not all cells in all columns. *"This pulls all columns"* can be somewhat ambiguous in that context. (If anyone else read this answer.) – user13500 Feb 28 '14 at 16:18
0

You could try this:

1) Add the existing code to a function so that you can pass in the column parameter.

2) tr.cells[0] should be changed to tr.cells[col] using the passed-in parameter.

3) change innerText to innerHTML as innerText doesn't work on some browsers.

function getCol(col) {
  var s = '';
  for (var i = 0; i < l; i++) {
    var tr = tab.rows[i];
    var cll = tr.cells[col];
    s += ' ' + cll.innerHTML;
  }
  return s;
}

console.log(getCol(1)) // 222 in my example

Fiddle

Andy
  • 61,948
  • 13
  • 68
  • 95