Jquery toggles multiple classes

I want to show / hide multiple divs in one class using jQuery toggle.

Currently the button shows / hides all divs. How can I get it to switch one div without making the class unique? Screenshot .

JQuery

$(".button").click(function() {
    $(".comment").toggle();
});

      

HTML:

<div class="comment">
    Comment 1
</div>
<button class="button">Show Comment</button>
<br/>
<div class="comment">
    Comment 2
</div>
<button class="button">Show Comment</button>

      

+1


source to share


1 answer


You need to find a comment regarding the selected item. In your case, this is the previous button element, so use prev()

with $(this)

(which clicked the button):

JSFiddle: http://jsfiddle.net/TrueBlueAussie/vgs2wsz2/1/

$(".button").click(function() {
    $(this).prev(".comment").toggle();
});

      



Note: ".comment" prev()

is not needed in this case, but makes it more obvious.

eg. this will do the same:

$(".button").click(function() {
    $(this).prev().toggle();
});

      

+2


source







All Articles