Wondering
Wondering

Reputation: 5086

How to select the <tr> which holds the <a> andchange the color

I have a table structure:

<table style="width: 100%;">
            <tr>
                <td>
                  <a href="#" class="xx">one</a>
                </td>
                <td>Two</td>
                <td>Three</td>

            </tr>
            <tr>
                <td>
                  <a href="#" class="xx">Four</a>
                </td>
                <td>Five</td>
                <td>Six</td>

            </tr>
            <tr>
                <td>
                  <a href="#" class="xx">Seven</a>
                </td>
               <td>Eight</td>
                <td>Nine</td>

            </tr>
        </table>

CSS:

 .yy
    {
     background-color: red;    
    }

Now the problem is if I click on the <a> its corresponding <tr> element (<tr> that holds the <a>) background should be red, again if I click on the same <a> it should come back to normal. How to identify the the <tr> on which the <a> is clicked.

EDIT: I tried: $(".yy").not($(this).parent().parent()).removeClass("yy"); $(this).parent().parent().toggleClass("yy"); it worked.

Upvotes: 1

Views: 99

Answers (2)

Russ Ferri
Russ Ferri

Reputation: 6589

I think closest() should get what you are looking for.

$('a').click(function() {
   var tr = $(this).closest('tr');
   tr.toggleClass('yy');
});

This way you do not have to assume anything about how nested the anchor is in the containing tr.

Example

Upvotes: 1

MoDFoX
MoDFoX

Reputation: 2134

$('a').live('click', function(){

$(this).parent().parent() //this is how you select the <tr> that the <a> is in

//first .parent() gets the <td> second .parent() gets the <tr>

});

Let me know if you need more. There might be a better way but I'm not positive.

Upvotes: 2

Related Questions