Home > Software engineering >  jquery toggleClass for multiple divs
jquery toggleClass for multiple divs

Time:09-30

I have 3 paragraphs and I need to toggle class for each. These 3 paragraphs contain the same class names like below.

<p >Click here</p>
<p >Content 1</p>

<hr>

<p >Click here</p>
<p >Content 2</p>

<hr>

<p >Click here</p>
<p >Content 3</p>

The problem

It will toggle all three items because of the same class name. I came up with an idea to add unique class to 'content' div, but I have to repeat my jquery code to toggle class only each item.

Any help? I need to show content one by one. Here is the fiddle

CodePudding user response:

Based on your HTML code the jQuery will indeed target all .content elements. So what you want is to target the first element with class .content.

You can do that by using the next() function.
Please note that .content needs to be a direct sibling of .news-btn to make this work.

$(".news-btn").click(function() {
  $(this).next(".content").toggleClass("show-content");
  /* $(this) refers to the element which triggered the event, in this case the .news-btn which is clicked
  .next() will target the next element in line. Note that .content needs to be directly after .news-btn
  toggleClass() speaks for itself */
});
.content {
  display: none;
}

.show-content {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p >Click here</p>
<p >Content 1</p>

<hr>

<p >Click here</p>
<p >Content 2</p>

<hr>

<p >Click here</p>
<p >Content 3</p>

Bonus:

If you only want to show one of the .content items, you can use this code. It does basically the same, expect it first hides all .content elements, and than adds the class to the first .content sibling.

$(".news-btn").click(function() {
  $(".content").removeClass("show-content"); 
  /* hide all .content elements */
  $(this).next().addClass("show-content");
  /* $(this) refers to the element which triggered the event, in this case the .news-btn which is clicked
  .next() will target the next element in line. Note that .content needs to be directly after .news-btn
  addClass() will add the class to the element */
});
.content {
  display: none;
}

.show-content {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p >Click here</p>
<p >Content 1</p>

<hr>

<p >Click here</p>
<p >Content 2</p>

<hr>

<p >Click here</p>
<p >Content 3</p>

  • Related