Jako
Jako

Reputation: 4901

jQuery - hide <tr> by clicking on link in <td>

I currently have a table that looks something like this...

 <table>
    <tr>
      <td>1</td>
      <td>2</td>
      <td><a href="#" class="remove">Remove</a></td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td><a href="#" class="remove">Remove</a></td>
    </tr>
    </table>

When clicking on the remove link, I would like to hide that current . This is the following code I've tried, but with no luck.

$(".remove").click(function() {

  $(this).parent("tr").hide();

}); 

Upvotes: 0

Views: 1644

Answers (3)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Use closest() instead of parent():

$(".remove").click(function() {
  $(this).closest("tr").hide();
}); 

Updated fiddle

Upvotes: 1

James Allardice
James Allardice

Reputation: 165971

The .parent() method will only look at the immediate parent. You need to go up one level further, with the .closest() method:

$(this).closest("tr").hide();

You could alternatively (just to give you an idea of what's going on) call .parent() twice:

$(this).parent().parent().hide();

The selector you pass to .parent() is used to return the parent element if it matches, rather than return the first ancestor that does match - notice that I've not passed anything to .parent() in the example above, which works just fine.

Here's a working example.

Upvotes: 4

Adil
Adil

Reputation: 148110

You need closest() function of jquery to see the closest up the hierarchy. Parent will look just one level.

$(".remove").click(function() {

  $(this).closest("tr").hide();

}); 

Upvotes: 5

Related Questions