catandmouse
catandmouse

Reputation: 11809

How to apply the same jQuery code to two instances of the same class?

For instance I have this code:

$('.note .exit').click(function() {
  $('.note').fadeOut();
});

And on my HTML there are two instances of .exit and .note. As in:

<div class="note">
        <img src="images/exit.png" class="exit"/>

        <p>Some text.</p>   
</div>

<div class="note">
        <img src="images/exit.png" class="exit"/>

        <p>Some other text.</p> 
</div>

The problem is when I click the close button (exit image) of one .note, the other .note also closes. How do I revise the code so that it only applies to that particular .note class that I am closing?

Upvotes: 1

Views: 67

Answers (3)

Simone Gianni
Simone Gianni

Reputation: 11662

Use $(this).parent().fadeOut() ... this will be the .exit on which the click happened.

Upvotes: 2

Tushar Ahirrao
Tushar Ahirrao

Reputation: 13115

Try this :

 $('.note .exit').click(function() {
  $(this).closest('.note').fadeOut();
});

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816404

Use .closest() [docs] to get the closest ancestor that matches a selector:

$('.note .exit').click(function() {
  $(this).closest('.note').fadeOut();
});

Given your structure, you could also use .parent() [docs].

Upvotes: 6

Related Questions