I'm setting up a very straightforward FAQ page with jQuery. Like so:
<h2>What happens when you click on this question?</h2> <p>This answer will appear!</p>
This is all inside a very specific div, so I'll be selecting the header with $('#faq h2')
. Simple, right? Click on the H2, and use this.next()
to make the next paragraph show up.
(The caveat with this page is that a non-programmer will be maintaining it, which is why I'm not using classes: there's no guarantee that any new entries would have the right classes in them.)
So! The problem:
<h2>What happens when you click on the next question?</h2> <p>That is an interesting conundrum.</p> <p>Because the maintainer is kind of long-winded</p> <p>and many answers will span a few paragraphs.</p>
So how, without adding in div
s and classes and whatnot, can I have my this.next()
routine select everything between the question-that-was-clicked-on and the next question (H2 header)?
I realise that this is an old question, but jQuery 1.4 now has nextUntil. So something like this should now work:
$('h2').click(function(){ $(this).nextUntil('h2').show(); })
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