Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get consecutive elements using jquery?

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?

like image 700
Samir Bhattacharjee Avatar asked Dec 28 '22 05:12

Samir Bhattacharjee


2 Answers

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/

like image 70
Rocket Hazmat Avatar answered Dec 31 '22 05:12

Rocket Hazmat


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();
 });
like image 28
mindandmedia Avatar answered Dec 31 '22 05:12

mindandmedia