Jquery select nth children of nth children

I have a table, and I want to do this when I find a cell, it highlights this cell and symmetric, for example, if I put the mouse in cell (3,1), it highlights this cell and (1,3). I have this code:

$('td').on('mouseover mouseout', function(){ $(this) .add($(this).parent().parent() .children()[$(this).index()]).toggleClass('hover'); }); 

Thus, I can select the correct row, but I need to select only the correct cell in this row, it is a symmetric cell. I tried with some selectors, but I cannot go to this cell.

Here is an example

+5
source share
4 answers

You can ork with index() ,

 $('td').on('mouseover mouseout', function () { $(this).toggleClass('hover'); if ($(this).index() !== $(this).parent().index()) { $('tr:eq(' + $(this).index() + ') td:eq(' + $(this).parent().index() + ')').toggleClass('hover'); } }); 

Demo script

+3
source

Try the following:

When you hover over cell (x, y), cell (y, x) gets the hover class as well

Check out demo

 $('td').on('mouseover', function(){ var that = $(this); that.addClass('hover'); var x = that.index(); var y = that.closest('tr').index(); $('table').find('tr').eq(x).find('td').eq(y).addClass('hover'); }).on('mouseout', function() { $('td').removeClass('hover'); }) 
+4
source
 $('td').on('mouseover mouseout', function () { var i = this.cellIndex, pi = this.parentNode.rowIndex, cell = this.parentNode.parentNode.rows[i].cells[pi]; $(this).add(cell).toggleClass('hover'); }); 

https://jsfiddle.net/1u3w7b3q/2/

+2
source
 $('td').on('mouseover mouseout', function(){ $(this).toggleClass('hover'); $index = $(this).index()+1; $index2 = $(this).parent().index()+1; $index != $index2?$('tr:nth-child('+$index+') > td:nth-child('+$index2+')').toggleClass('hover'):''; }); 

jsfiddle: https://jsfiddle.net/aEwE4/106/

0
source

All Articles