Prashant Prashant - 4 months ago 77
HTML Question

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

I have a html table as below:


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?


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");