MHS
MHS

Reputation: 2350

Javascript - How to get particular column's data of a table?

I have multiple tables on my page. I want to pick a particular column from all tables but I am unable to understand the problem with my piece of code.
It looks like this:

function getTableColumnValues(){
    var table, columnValue, tableId
    table=document.getElementsByTagName('table');
    for(l=1;l<table.length;l++){
        tableId = table[l].id
        if(tableId != ""){
            columnValue = $(tableId+'>tbody>tr>td:nth-child(2)').each(function(){ // Here 2 is the column number of which the data I want. 
                $(this).text()
                });
            console.log('TABLE ID: ',tableId);
            console.log("COLUMN VALUE: ",columnValue);
        }
    }
}

but my debugger's console shows this:

TABLE ID: id_219
COLUMN VALUE: Object[]

TABLE ID: id_220
COLUMN VALUE: Object[]

TABLE ID: id_221
COLUMN VALUE: Object[]

Is it ok to place jquery inside javascript code?
Please help me, where I am doing it wrong?

Upvotes: 0

Views: 13496

Answers (3)

mplungjan
mplungjan

Reputation: 177684

Here is my suggestion

  1. get only tables with IDs
  2. use jQuery .each on the tables and their cells
  3. pass the column you want for future flexibility

Live Demo

function getTableColumnValues(col){
    var columnValues=[];
    $('table[id]').each(function() {
        $('tr>td:nth-child('+col+')',$(this)).each(function() {
          columnValues.push($(this).text());
        });
    });
    return columnValues;
}
var vals = getTableColumnValues(2);
window.console && console.log(vals);

Upvotes: 2

Nish
Nish

Reputation: 1137

function getTableColumnValues(){
    var table=document.getElementsByTagName('table');
    for(l=1;l<table.length;l++){
        for(i=1;i<table.rows.length;i++){
           console.log(table.rows[i].cells[2]);
        }
    }
}

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337550

You need to place the console.log for the value within the each, as that it the iteration you're looking at:

for(l=1;l<table.length;l++){
    tableId = table[l].id
    if(tableId != ""){
        console.log('TABLE ID: ',tableId);
        $(tableId+'>tbody>tr>td:nth-child(2)').each(function(){ // Here 2 is the column number of which the data I want. 
            var columnValue = $(this).text();
            console.log("COLUMN VALUE: ", columnValue);
        });
    }
}

The reason it is currently displaying Object[] is because the return value of each() is a plain jQuery object - you need to deal with the target element of the iteration within the handler function.

Also, take note of @mplungjan's advice regarding the odd mix of plain javascript and jQuery.

Upvotes: 2

Related Questions