GregH
GregH

Reputation: 12878

jQuery - How many cells in a row

Is there a way in jQuery to tell how many cells are in a selected row? For example, I am iterating through the rows via:

$("#statsId > table tbody tr").each ( function() {
    var secondCol = $(this).find('td:nth-child(2)').html();
    var thirdCol= $(this).find('td:nth-child(3)').text();

and want to retrieve the second and third cell values. However when I do this iteration the cell values are coming back null when I know they are not. I thought if there was a way to verify the number of cells/columns in the selected row, I could at least verify that there are three cells in the selector. Or perhaps my selector for "secondCol" and "thirdCol" is wrong. Any help is appreciated.

Upvotes: 1

Views: 3723

Answers (4)

Doug Neiner
Doug Neiner

Reputation: 66201

You can use this to test:

if( $(this).children('td').length >= 3 ) {
   ...
}

But also play with using :eq() as well:

var secondCol = $(this).find('td:eq(1)').html();
var thirdCol= $(this).find('td:eq(2)').text();

Upvotes: 3

Jon Cram
Jon Cram

Reputation: 17309

var currentRow = <jQuery object for current row>;
var currentRowCellCount = $('td', currentRow).length;

This simply gives you access to the total number of td elements in a given row.

Upvotes: 1

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124828

$("#statsId > table tbody tr").each(function() {
    var cells = $(this).find('td').size();
    ...

Upvotes: 0

Paul Creasey
Paul Creasey

Reputation: 28864

$('#myRow').children().size()

This is the most simple approach i can think of, but it's not infallable.

Upvotes: 1

Related Questions