How to get sequential elements using jquery?
Please view 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 one p-tag after the h1 tag when clicking on the h1 tag. But I need to switch the display of consecutive p-tags (from one to three when clicking on the header)
What should jQuery code be?
+4
4 answers
I played you a fiddle: http://jsfiddle.net/hMsXz/2/
here is the code for saving clicks:
$('.aclass h1').click(function(){ $(this).nextUntil('h1','p').toggle(); }); +3
Use .nextUntil :
$('.aclass h1').click(function() { $(this).nextUntil('h1', 'p').toggle(); // Selects all p tags after the h1 // stops when it hits an h1 }); +4