So I have a page that displays multiple “posts” that include “comments”. My code:
<div class="post">
This is a post
<span class="toggleComments">Hide/Show Comments</span>
<div class="comment">This is a comment</div>
</div>
<div class="post">
This is another post
<span class="toggleComments">Hide/Show Comments</span>
<div class="comment">This is another comment</div>
<div class="comment">This is a third comment</div>
</div>
So here is my problem: I have a span with the class toggleComments included which “toggles” the comment div. I have achieved this with:
$('.toggleComments').click(function(){
$('.comment').toggle();
});
The thing is that by clicking the link, the .comment div form ALL the comments hides/appears, is there a way to make it so the comments from the same post toggle the effect, and not the comments from all the posts?
EDIT: Updated with the .toggleComments line
Assuming
.toggleCommentsis inside of the same.postthat you want to toggle the comment on, you would find the parent.postand then inside of that find the appropriate comment to toggle:As you can see from the other answers, there are many approaches to finding the
.commentobjects in the same containing div. The advantage of doing it this way rather than referencing siblings is that it will find them anywhere in the common.postparent even if the layout of the HTML is tweaked somewhat in the future. I prefer to make this type of code as robust as possible against future HTML tweaks as long as it doesn’t compromise anything important.