tags:

views:

39

answers:

3

Suppose I have

<table>
  <tr>
    <td><a class='ilink'> link text </a></td>
    <td></td>
    <td></td>
  <tr>
  <tr>
    <td><a class='ilink'> link text </a></td>
    <td></td>
    <td></td>
  </tr>
</table>

in the jquery code, after clicking the link, I want to highlight the entire table row that the link is in. But how can I find it?

+6  A: 

You can do it with .closest() like this:

$("a.ilink").click(function() {
  $(this).closest("tr").addClass("highlight");
});

If you have a lot of rows, this would be more efficient (one copy of this vs. one for every <a>):

$("table").delegate("a.ilink", "click", function(){
  $(this).closest("tr").addClass("highlight");
});
Nick Craver
Good answer. I was going to recommend `parentsUntil()` but was unaware its collection contains all parent items as it walks up the DOM tree. closest makes perfect sense. +1
KP
A: 
#EDIT remove...  better options listed
A Rad
+1  A: 
$(document).ready(function(){
    $('a.ilink').click(function() {
        $('tr').removeClass('highlight');
        $(this).closest('tr').addClass('highlight');
    });
 });

Then you will need the highlight css class defined:

.hightlight { background-color:red; }
amurra