Phil
Phil

Reputation: 4069

Create array of table cell values jQuery

I have the following code, which I'm using to create an array of all the tr's in the tbody area of a table.

var $table = $('#mytable');
var $rows = $table.find("tbody tr");

It works fine and contains the data from the table. However, I want to loop over each row and create an array of the value of each cell in that row. I've tried:

for(x=0;x<$rows.length;x++)
{
    var aCells = $rows[x].find("td");
    alert(aCells.length);
}

But the console is showing an error stating that Object # has no method 'find'

Can anyone help me? I just want to loop over each row in the tbody one at a time and create an array of the cell values within that row so I can access a specific cell on each loop.

Upvotes: 0

Views: 764

Answers (3)

lex82
lex82

Reputation: 11297

$rows is not an array. It's a jQuery object. Use $rows.eq(x) instead. See the documentation of .eq()

Upvotes: 2

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

You can use .each() to iterate through the rows and you can access its td elements by using the $(this) reference.

Try

$rows.each(function(){
    var aCells = $(this).find("td");
    alert(aCells.length);
});

Upvotes: 2

epascarello
epascarello

Reputation: 207501

This returns DOM not a jQuery object

$rows[x]

You want to use eq()

$rows.eq(x).find("td");

or just use each()

$rows.each(function(){
    var cells = $(this).find("td");
});

Upvotes: 3

Related Questions