Toggle card content for only direct child with jQuery?

I have about 9 cards on my site. Here is the structure of one card:

<div class="serviceCard">
  <div class="serviceContent">
    blah blah blah
  </div>
  <a class="serviceToggle">Learn More</a>
</div>

I am using the below jQuery to toggle the content of the card, but it’s affecting all my cards since they all use the same class. How can I adjust my code so that it only affects the card that I am clicking on?

jQuery(document).ready(function() {
    jQuery(".serviceToggle").click(function(){
     jQuery(".serviceContent").toggle();
    });
});

>Solution :

Inside the .click function, you can use jQuery(this) to refer to the current element and .find other elements starting from there:

jQuery(document).ready(function() {
  jQuery(".serviceToggle").click(function(){
    jQuery(this).parent()
    .find(".serviceContent").toggle();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="serviceCard">
  <div class="serviceContent">
    blah blah blah
  </div>
  <a class="serviceToggle">Learn More</a>
</div>

Leave a Reply