Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery nextAll -- Click on h-element toggles all p-elements until next h

I'm creating an FAQ page where the answer is toggled by clicking on the question. The question is h3 and the answer is several p-elements. Like this:

<h3>The First Question</h3>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>

<h3>The Second Question</h3>
<p>Answer Paragraph</p>
<p>Answer Paragraph</p>

How can I toggle all p-elements belonging to a certain question? My JS toggles all following p-elements on the page:

$(document).ready(function(){
    $("p").hide();
    $("h3").click(function(){
        $(this).nextAll("p").toggle();
    });
});

I cannot use div's or classes).

like image 923
Christoph Avatar asked Jul 03 '09 15:07

Christoph


1 Answers

The best way to do this is using each and iterating until you get to the next element that should stop the iteration. Returning false during an each stops the iteration. Using filter allows you to check the type of the element in the iteration and respond appropriately.

$(function() {
   $("p").hide();
   $("h3").click(function() {
       $(this).nextAll().each( function() {
           if ($(this).filter('h3').length) {
              return false;
           }
           $(this).filter('p').toggle();
       });
   });
});
like image 176
tvanfosson Avatar answered Sep 20 '22 13:09

tvanfosson