Espen Arnoy
Espen Arnoy

Reputation: 157

Element targeting with jQuery

I am trying to use jQuery to show a div when the user clicks an "a" element. I´m struggling however because I´m not able to target the div precisely.

Looking at the code below, you see that my program lists offers (Offer#1 & Offer#2). Right below the offer div, there is the comments div (where the comments for the offer is shown). The .comment_icon element can be clicked to show/ hide the comments.

<div id="offer">
Offer#1 goes here
<a href="#" class="comment_icon">Show comments</a>
</div>
<div class="comments">
Comments for Offer#1 goes here
</div>

<div id="offer">
Offer#2 goes here
<a href="#" class="comment_icon">Show comments</a>
</div>
<div class="comments">
Comments for Offer#2 goes here
</div>

$('.comment_icon').toggle(
    function() {
        $('.comments').slideDown();
    },
    function() {
        $('.comments').slideUp();
    }
);

My problem is that when .comment_icon element is clicked, it will show all div´s with the .comments class. However, I just want the one belonging to the respective offer to show when the .comment_icon is clicked.

Is there any way to do this kind of tartgeting?

Upvotes: 2

Views: 488

Answers (1)

Doug Neiner
Doug Neiner

Reputation: 66191

First, you shouldn't use two elements with the same id, but lets just say you keep it that way, this is what you want:

$('.comment_icon').click(function(e){
  $(this).closest('div#offer').next('.comments').slideToggle();
  e.preventDefault();
});

Like I said, you want to change id='offer' to class='offer' and then just change the selector in my answer to div.offer.

Upvotes: 6

Related Questions