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.
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();
});
$('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
).
How about:
$('td').click(function () {
var nextCell = $(this).parent().next().find("td:nth-child(whatever)");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With