Damon Daisley Wilson
Damon Daisley Wilson

Reputation: 85

Hide Only 1 Parent When Child Div is clicked

Having trouble when attempting to use .closest().

I have a repeating parent/child div on my page and when I click on the child I want the parent to be hidden. But only the parent of the child who was clicked.

What's happening now is ALL parents on the page are being hidden.

Here's the code: HTML

<div class="parent">
    <a href="#" class="child">I'm the child</a>
</div>
<div class="parent">
    <a href="#" class="child">I'm the child</a>
</div>
<div class="parent">
    <a href="#" class="child">I'm the child</a>
</div>

JQuery

$( ".child" ).click(function() {
  $( ".child" ).closest( ".parent" ).fadeOut();
});

Any ideas what I'm doing wrong? Thanks in advance!

Upvotes: 2

Views: 343

Answers (1)

Andrew Ngo
Andrew Ngo

Reputation: 762

Use $(this) to reference the element that was clicked.

$(".child").click(function() {
    $(this).closest(".parent").fadeOut();
});

Upvotes: 4

Related Questions