jQuery select next TD or cell in a table

jQuery select next cell or TD in a table


Cell 1 (index: 0) Cell 2 (index: 1) Cell 3 (index: 2)
Cell 4 (index: 3) Cell 5 (index: 4) Cell 6 (index: 5)
Cell 7 (index: 6) Cell 8 (index: 7) Cell 9 (index: 8)

Step 1: set up the table with correct id and class

First, we need to set up the html table that contains the TD cells the jQuery script will be traversing.

There are two things that are important to notice here:

  • The id attribute in the table tag: id="table"
  • The class property in each TD cell: class="tablecell"
  • The index value is the position of the cell within the table (zero-based position)
<table id="table">
        <td class="tablecell">Cell 1 (index: 0)</td>
        <td class="tablecell">Cell 2 (index: 1)</td>
        <td class="tablecell">Cell 3 (index: 2)</td>

Step 2: traversing the table cells and selecting the next TD using jQuery

	var cells = $('#table .tablecell');
	var i =0;
		if( !$(cells[i]).length ){
			i = 0;
		$('#table .tablecell').css('backgroundColor', '#fff');
		$(cells[i]).css('backgroundColor', '#ddd');

		i = i+1;

Here is what happens when the button with the id "selectnextcell" is clicked:

  • The color of all the TD cells is reset to blank with:
    $('#table .tablecell').css('backgroundColor', '#fff');
  • We apply the new background color to the cell that has its index value equals to i
  • i starts from 0 (var i = 0) and i is incremented each time the button is clicked (i = i+1)
  • If ($(cells[i]).length) returns nothing, it means we have reached the last cell of the table and that we have go back to the first TD