最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

cells - Javascript get entire 2nd column - Stack Overflow

programmeradmin0浏览0评论

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);
}

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);
}
Share Improve this question edited Jul 27, 2017 at 13:47 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Feb 28, 2014 at 13:57 JohnBJohnB 1511 gold badge2 silver badges13 bronze badges 5
  • 1 tab.rows.length; ?? – Grijesh Chauhan Commented Feb 28, 2014 at 14:00
  • Should work with cells[1] - there is probably an empty column that you are missing. – tucuxi Commented Feb 28, 2014 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 Commented Feb 28, 2014 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 Commented Feb 28, 2014 at 16:13
  • 1 @sємsєм: No, he will get the column, not the row. – user13500 Commented Feb 28, 2014 at 16:14
Add a comment  | 

3 Answers 3

Reset to default 10

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:

  • INNERTEXT VS. TEXTCONTENT
// 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(',');
}

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

发布评论

评论列表(0)

  1. 暂无评论