Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Get next table cell vertically

How can I use jQuery to access the cell (td) immediately below a given cell in a traditional grid-layout html table (i.e., one in which all cells span exactly one row and column)?

I know that the following will set nextCell to the cell to the immediate right of the clicked cell because they are immediate siblings, but I am trying to retrieve the cell immediately below the clicked cell:

$('td').click(function () {
    var nextCell = $(this).next('td');
});

Preferably I would like to do it without any use of classes or ids.

like image 211
Devin Burke Avatar asked Jan 12 '12 18:01

Devin Burke


3 Answers

Try this:

$("td").click(function(){
  // cache $(this);
  var $this = $(this);

  // First, get the index of the td.
  var cellIndex = $this.index();

  // next, get the cell in the next row that has
  // the same index.
  $this.closest('tr').next().children().eq(cellIndex).doSomething();
});
like image 80
Kevin B Avatar answered Nov 12 '22 22:11

Kevin B


$('td').click(function () {
  var index = $(this).prevAll().length
  var cellBelow = $(this).parent().next('tr').children('td:nth-child(' + (index + 1) + ')')
});

index is the 0-based index of the cell in the current row (prevAll finds all the cells before this one).

Then in the next row, we find the nth-child td at index + 1 (nth-child starts at 1, hence the + 1).

like image 37
mbillard Avatar answered Nov 12 '22 23:11

mbillard


How about:

$('td').click(function () {
    var nextCell = $(this).parent().next().find("td:nth-child(whatever)");
});
like image 1
Adaz Avatar answered Nov 12 '22 23:11

Adaz