Prashant Prashant - 1 month ago 24
HTML Question

jQuery .nextAll() is not working with html table columns

I have a html table as below:

<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
</table>


On click of a td I am changing the color of it's next 4 td's and for that I have done it in jquery as below:

$(this).nextAll("td").slice(0, 4).addClass("selected");


Above code is working if I click on 1st TD then it selects further 4 td's but if I click on 4th td then it selects only 5th td. I want it to select another 3 td's in next row as well.

Please tell me how can I fix this?

Answer

jQuery .index() method returns the index of passed element in the current set. By using returned index you can .slice() the collection, this is more efficient than querying the DOM on each click, especially when you have a big table:

var $tds = $('#table td').on('click', function() {
   var i = $tds.index(this);
   $tds.slice(++i, i+4).addClass("selected");
});

http://jsfiddle.net/MamYX/

Comments