Matthew
Matthew

Reputation: 15642

Parent selector in jquery

I have a table row that needs to be hidden when the anchor with class removerow is clicked.

<tr>
  <td>Product Name</td>
  <td><a class="removerow">Remove</a></td>
</tr>

I've been trying this, but it doesn't work:

$("a.removerow").click(function(){
  (tr > this).hide();
});

How can I select the entire table row with a child of .removerow.

What am I doing wrong?

Thanks.

Upvotes: 4

Views: 756

Answers (2)

Powerlord
Powerlord

Reputation: 88796

jQuery doesn't have a parent selector, but it does have a parent function.

Also, the tr is not the direct parent of the link. Instead, it's two levels up (td is the first parent)

$("a.removerow").click(function(){
    // Called twice (first is td, second is tr)
    $(this).parent().parent().hide();
});

If there are no other trs in the hierarchy, you could also use

$("a.removerow").click(function(){
    // Called twice (first is td, second is tr)
    $(this).parents('tr').hide();
});

If the tr has a class on it, you could do this:

$("a.removerow").click(function(){
    // Called twice (first is td, second is tr)
    $(this).parents('.ClassNameHere').hide();
});

Upvotes: 3

user113716
user113716

Reputation: 322492

jQuery's closest(selector) function will traverse upward and return the nearest selector provided.

(If the element clicked is the same as the given selector, then it returns that.)

http://api.jquery.com/closest/

$("a.removerow").click(function(e){
    $(this).closest('tr').hide();
    e.preventDefault();
});

The e.preventDefault() will disable the default behavior of the a element.

Upvotes: 4

Related Questions