Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .each() to toggle hidden elements [closed]

Very new to JQuery, and am struggling to understand .each().

I would like to be able to click on any heading, and have the paragraph under that heading appear, and then disappear. At the moment, I can only get the first paragraph to toggle.

My code is:

<script>
$(document).ready(function(){
  $("h2").click(function(){
    $("#hidden").each(function(){
        $(this).toggle();      
    });
  });
});

</script>

<h2>HEADING 1</h2>
<div id="hidden" style="display:none">
<p>paragraph 1</p>
</div>

<h2>HEADING 2</h2>
<div id="hidden" style="display:none">
<p>paragraph 2</p>
</div>

Thanks very much for any help!

like image 313
user1573524 Avatar asked May 22 '26 16:05

user1573524


1 Answers

ID of ane element must be unique use class attribute to group similar elements

<h2>HEADING 1</h2>
<div class="hidden" style="display:none">
<p>paragraph 1</p>
</div>

<h2>HEADING 2</h2>
<div class="hidden" style="display:none">
<p>paragraph 2</p>
</div>

then also there is no need to use a each loop, you can call .toggle() in the jQuery wrapper returned by the selector $('.hidden')

$(document).ready(function(){
  $("h2").click(function(){
    $('.hidden').toggle();      
  });
});

Update Didn't read the complete question the question seems to be how to toggle the next div

$(document).ready(function(){
  $("h2").click(function(){
    $('.hidden').hide();
    $(this).next().toggle();      
  });
});

Demo: Fiddle

like image 119
Arun P Johny Avatar answered May 25 '26 04:05

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!