Devin Burke Devin Burke - 2 months ago 18
jQuery Question

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.

Answer

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();
});
Comments