Using jQuery "this" plus a CSS selector?

APAD1 picture APAD1 · Jun 10, 2014 · Viewed 15k times · Source

I am writing a script to show/hide a section within a div. I have 3 of these divs with hidden sections but was hoping to use one function to control all 3.

Here's what I have right now:

$('.rates, .hours, .otherinfo').click(function() {
    $('.expand').toggle();
});

Here's the HTML:

<div class="rates">
    <h2>Rates</h2>
    <div class="expand">
        <p>Text in here is hidden by default.</p>
    </div>
</div>
<div class="hours">
    <h2>Hours</h2>
    <div class="expand">
        <p>Text in here is hidden by default.</p>
    </div>
</div>
<div class="otherinfo">
    <h2>Other Info</h2>
    <div class="expand">
        <p>Text in here is hidden by default.</p>
    </div>
</div>

And CSS:

.expand {
    display:none;
}

Obviously, this shows the "expand" div for all 3 of the divs when you click on any of them. Is there a way to incorporate this into the selector. Something like this'.expand'?

Thanks!

Answer

Nick picture Nick · Jun 10, 2014

$(this).find('.expand').toggle()