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).
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();
});
});
});
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