Algorithm
Algorithm

Reputation: 329

How to set an event on the parent element using jQuery

help me figure out how to set an event on the parent element (<tr>) I can't find the error in the condition

<script type="text/javascript">
$('table tbody tr').each(function(){
     $(this).find('a:first').click(function(){
        if($(this).parents().get(1).tagName == 'TR') {
         $(this).parents().get(1).find('tr').css('background', 'red'); //What's wrong?
        }
});
</script>

<table>
   <tbody>
      <tr>
         <td><a href="#">text</a></td>
         <td>text</td>
      </tr>
   </tbody>
</table>

Unfortunately, the formatting, I don't see any more special tag

Upvotes: 1

Views: 657

Answers (7)

Shikiryu
Shikiryu

Reputation: 10219

$('table tbody tr').each(function(){
     $(this).find('a:first').click(function(){
        $(this).css('background', 'red');
     });
});

easy one.

Upvotes: 0

Ayaz Alavi
Ayaz Alavi

Reputation: 4835

hey you are missing closing }); for each statement. Here is the correct version of your code

$('table tbody tr').each(function(){
     $(this).find('a:first').click(function(){

           if($(this).parents().get(1).tagName == 'TR') {
               $($(this).parents().get(1)).css("background-color", 'red'); //What's wrong?
           }
      });       
 });

Working Example

EDIT: you can shorten above code very easily like assigning a class to anchor tag.

<a class="bindclick" href="#"></a>

$(".bindclick").bind("click", function(){
   var parent = $(this).parents("tr").get(0);
            OR
   var parent = $(this).closest("tr"); // http://api.jquery.com/closest/
   $(parent).css("background-color","red");
});

Upvotes: 1

sod
sod

Reputation: 3928

Edit: This works:

$(function() {
  $('tr a:first').click(function() {
    $(this).parents('tr:first').css({background:'red'});
  });
});

Upvotes: 0

Umakanta.Swain
Umakanta.Swain

Reputation: 1117

$('table tbody tr').each(function(){
          var $this = $(this);
          $this.find('a:first').click(function(){
             $this.css('background', 'red');
        });
});

Upvotes: 0

o15a3d4l11s2
o15a3d4l11s2

Reputation: 4049

Not completely sure about this, but I think that when you call $(this) inside the second function for clicking the a tag, $(this) is the a tag itself, and not the $(this) which is in the outer function the tr element.

Upvotes: 0

Marko
Marko

Reputation: 72222

$("table tr a:first").click(function() {
    $(this).closest("tr").css('background', 'red');
});

Upvotes: 1

Reigel Gallarde
Reigel Gallarde

Reputation: 65254

$('table tbody tr').each(function(){
     var $this = $(this);
     $this.find('a:first').click(function(){
         $this.css('background', 'red');
     });
});

crazy demo

Upvotes: 1

Related Questions