tags:

views:

64

answers:

4

The snippet below repeats many times per page. When I click .load_comments, how I can select .answer_comments?

I guess the easiest way to do it is to select first the parent (.single_answer) and then just use descendant selectors to select the div I need. I'm having problems selecting the .single_answer parent. Using $(".single_answer:parent") selects ALL those divs on the page, which makes sense since they are all parents of something.

I'm not sure if one can use something along the lines of $(this).parent ... ? I can't quite figure out the syntax but I know I'm close.

Thanks for any pointers.

<div class="single_answer">
<p class="answer_author">On 12 Nov X said: </p>
<p class="answer_text">Bla</p>
<a href="#" id="" onclick="return false" class="load_comments">View 2 Comments</a>
<a href="#" id="aid_16-qid_54" onclick="return false" class="comment">Comment</a>
<div class="container answer_form_container"> </div>
<div class="container answer_comments"> </div>
</div>
A: 

parent is a method and not an attribute. Try $(this).parent() instead.

Gumbo
A: 

If you know the class name why not select the element directly $('.answer_comments') instead of passing through the parent? Or alternatively give the element you would like to select an unique id and then: $('#my_unique_element')

Darin Dimitrov
+4  A: 

Try this:

$('.single_answer .load_comments').click(function() {
    $(this).closest('.single_answer').find('.answer_comments');
    return false;
}

This will be a bit more robust to changes in your structure: it allows for finding the nearest ancestor (parent, grandparent, etc).

Alternatively, if you know that the answer_comments are always another child of the same parent:

$(this).siblings('.answer_comments')

...will find it too.

nickf
I never knew about `closest()` !
alex
A: 

I think this is what you're after.

$('.load_comments').click(function() { 

$(this).siblings('.answer_comments').html('this text will appear in the appropriate .answercomments div');

});
davewasthere