November 28, 2011

jquery how to change class of one <td> based on id of another <td>

Question by Martlark

I have two tables and I want to highlight a cell in table 1 when I hover over another cell in table 2. Not sure how to get there from here. I’m thinking I should take the id from table 2 and look for the same id thing in table 1 and add the highlight class.

<!DOCTYPE html> 
<html> 
<head> 
  <style> 
.cell {    background-color:#FFCC00 } 
.cell-highlight {    background-color:green } 
</style> 
  <script src="http://code.jquery.com/jquery-latest.js"></script> 
</head> 
<body> 

<table border='1' id='table-1'>
    <tr>
        <td class='cell' id='cell-0-0'>Cell 0,0</td><td class='cell' id='cell-0-1'>Cell 0,1</td>
    </tr>
    <tr>
        <td class='cell' id='cell-1-0'>Cell 1,0</td><td class='cell' id='cell-1-1'>Cell 1,1</td>
    </tr>
</table>
<br/>
<table border='1' id='table-2'>
    <tr>
        <td class='cell' id='t2cell-0-0'>2 Cell 0,0</td><td class='cell' id='t2cell-0-1'>2 Cell 0,1</td>
    </tr>
    <tr>
        <td class='cell' id='t2cell-1-0'>2 Cell 1,0</td><td class='cell' id='t2cell-1-1'>2 Cell 1,1</td>
    </tr>
</table>
<script> 
  var id;
  $("td.cell").mouseover(function() { 
    id=$(this).find("id");
    $(this).addClass('cell-highlight' ); 
  }).mouseout(function() { 
    $(this).removeClass('cell-highlight' ); 
  }); 

</script> 

</body> 

Answer by Starx

Make the following changes it your code

$("td.cell").mouseover(function() { 
    id=$(this).attr("id");
    $(this).addClass('cell-highlight' ); 
    secondid = "#t2"+id;
    $(secondid).addClass('cell-highlight');
  }).mouseout(function() { 
    $(this).removeClass('cell-highlight' );
    id=$(this).attr("id");
    secondid = "#t2"+id;
    $(secondid).removeClass('cell-highlight'); 
}); 

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!