Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the p tag within a div with an id, using a sibling h3 tag with a class

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!

like image 478
Dan Solo Avatar asked Feb 22 '23 12:02

Dan Solo


1 Answers

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');
});
like image 97
BoltClock Avatar answered May 02 '23 18:05

BoltClock