Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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();
    });
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading