Please look through the following code snippet -
HTML
<div class="aclass">
<h1>This is heading one</h1>
<p>This is paragraph one, this will be hidden automatically</p>
<p>This is paragraph two, this will be hidden automatically</p>
<p>This is paragraph three, this will be hidden automatically</p>
<h1>This is heading two</h1>
<p>This is paragraph four, this will be hidden automatically</p>
<p>This is paragraph five, this will be hidden automatically</p>
</div>
CSS
.aclass p {display:none;}
JS
$(document).ready(function(){
$('.aclass h1').click(function(){
$(this).next('p').toggle();
});
});
This JS code toggles the display of a single p tag after the h1 tag when clicked on the h1 tag. But I need to toggle the display of consecutive p tags (one to three when clicked on heading one)
What should be the jQuery code to do so?
Use .nextUntil
:
$('.aclass h1').click(function() {
$(this).nextUntil('h1', 'p').toggle(); // Selects all p tags after the h1
// stops when it hits an h1
});
DEMO: http://jsfiddle.net/dt7LH/
I played the fiddle for you: http://jsfiddle.net/hMsXz/2/
here the code for saving clicks:
$('.aclass h1').click(function(){
$(this).nextUntil('h1','p').toggle();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With