This is heading one

<...">

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
source share
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
source

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/

+4
source

I assume your point is to expand / collapse all the <p> tags under the <h1> click?

Use nextUntil('h1') to select all sibling elements before the <h1> .

+2
source

Use .nextUntil introduced in jQuery 1.4

 $(document).ready(function(){ $('.aclass h1').click(function(){ $(this).nextUntil('h1').toggle(); }); }); 
+1
source

Source: https://habr.com/ru/post/1398304/


All Articles