Margo Eastham
Margo Eastham

Reputation: 655

jquery class selector capture only the clicked element within the class

Here's the demo: https://jsfiddle.net/9fnh6ffy/

Here's the HTML:

<p><a href="#" class="new-answer">New answer</a></p>
<div class="answer-box">
</div>

<p><a href="#" class="new-answer">New answer</a></p>
<div class="answer-box">
</div>

<p><a href="#" class="new-answer">New answer</a></p>
<div class="answer-box">
</div>

I want whenever the .new-answer link is clicked, the corresponding .answer-box underneath it is opened. However I don't want to select it relatively such as using $(this).parents('p').next().toggle because I don't want to get into problem later debugging if I change the DOM.

Upvotes: 0

Views: 401

Answers (2)

Milind Anantwar
Milind Anantwar

Reputation: 82231

You need to traverse to parent p element and then target immediate next sibling:

$(this).parent().next().toggle();

Working Demo

Update: As the Dom structure may vary:

$(this).parent().nextAll('.answer-box').first().toggle();

Working Demo

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Since you said you don't want dom relationship to be used another approach could be is to use a attribute value. For example you can use a data-id attribute where you specify a number, where the same number will be associated to the related new-answer and answer-box element.

$(document).ready(function() {
  $('a.new-answer').click(function() {
    var id = $(this).data('id');
    $('.answer-box[data-id="' + id + '"]').toggle();
  });
});
.answer-box {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p><a href="#" class="new-answer" data-id="1">New answer</a></p>
<div class="answer-box" data-id="1"></div>

<p><a href="#" class="new-answer" data-id="2">New answer</a></p>
<div class="answer-box" data-id="2"></div>

<p><a href="#" class="new-answer" data-id="3">New answer</a></p>
<div class="answer-box" data-id="3"></div>

Upvotes: 1

Related Questions