Big McLargeHuge
Big McLargeHuge

Reputation: 16056

jQuery select first accordion in each tab

I have a page that uses jQuery tabs. Each tab contains one or more jQuery accordions, which are generated dynamically, in addition to other stuff. Example:

<div id="tab1" class="tab">
    <div>
        Some stuff
    </div>
    <div class="accordion">
        I am an accordion
    </div>
</div>
<div id="tab2" class="tab">
    <div class="accordion">
        I am also an accordion
    </div>
    More stuff
    <div class="accordion">
        I am also an accordion
    </div>
</div>

I would like the first accordion in each tab to remain open, while the others (if there are any) are collapsed. I have tried:

$('.tab .accordion:first')

which only selects the first accordion on the page (obviously). I also tried:

$('.tab .accordion:first-child')

This selects the first accordion in tab2 but it doesn't select the one in tab1 because there's some stuff above it. I've also tried:

$('.tab > .accordion').filter(':first-child')
$('.tab').children('.accordion:first-child')

Along with about every combination of selectors I can think of. At this point my brain is fried. Before you point me to a duplicate question, none of these are asking the same question exactly:

JQuery Tab each Selected tab first text box focus

jquery select first child with class of a parent with class

jQuery selector for each first element on every parent

jQuery Selecting the first child with a specific attribute

The difference in my case is I have very little control over what content shows up in these tabs.

Upvotes: 0

Views: 1469

Answers (2)

Alon Eitan
Alon Eitan

Reputation: 12025

Try this:

 $('.accordion:first', '.tab')

Upvotes: 0

David Thomas
David Thomas

Reputation: 253318

I'd suggest:

$('.tab').find('.accordion:first');

JS Fiddle proof-of-concept.

Upvotes: 1

Related Questions