Apologies if the title above is a little convoluted, writing these things in plain English is often more difficult than the problem within!
I'm sure this is a fairly basic issue but I'm getting a bit tied up with jQuery selectors and hierachy and can't see the wood for the trees now...it's a classroom exercise so I'm stuck with the HTML code as it is.
I'm trying to hide/display the paragraphs underneath a H3 heading by double clicking the H3 heading.
<div class="chapter" id="chapter-preface">
<h3 class="chapter-title">Preface</h3>
<p>Blah, blah, blah, blah, blah</p>
<p>Blah, blah, blah, blah</p>
<p>Blah, blah, blah</p>
<p>Blah</p>
</div>
<div class="chapter" id="chapter-1">
<h3 class="chapter-title">Chapter 1</h3>
<p>Rhubarb, rhubarb, rhubarb, rhubarb, rhubarb, rhubarb</p>
<p>Rhubarb, rhubarb, rhubarb</p>
</div>
The closest I've come so far is the following jQuery code:
$('.chapter-title').dblclick(function() {
$('div p').toggleClass('hidden');
});
but as is probably fairly evident this only has the effect of hiding all p tags under both of the divs. I want it to just hide the p tags under the relevant H3 heading that was double clicked. I've tried using 'this' but evidently incorrectly as it didn't have the desired effect.
I guess I need to somehow select the parent div of the H3 tag clicked on and the unique id associated with it and then apply the hide/display event to any child p tags within....any suggestions?
Cheers!
You can simply use .nextAll()
or .siblings()
to pick all the p
elements following that h3
in the parent div
, without actually selecting the parent div
:
$('.chapter-title').dblclick(function() {
$(this).nextAll('p').toggleClass('hidden');
});
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