jQuery Select Table Column or Row

Table rows are pretty easy to work as all the td elements are contained within one tr, but how would you grab all the tds in a single column? Why, by using these selectors of course!

$.fn.row = function(i) {
    return $('tr:nth-child('+(i+1)+') td', this);
}
$.fn.column = function(i) {
    return $('tr td:nth-child('+(i+1)+')', this);
}

// example - this will make the first column of every table red
$(document).ready(function() {
    $('table').column(0).css('background-color','red');
});

I like my selectors zero-based, but you can get rid of the +1 if you don’t like it.

2 thoughts on “jQuery Select Table Column or Row

Leave a Reply

Your email address will not be published. Required fields are marked *